//加载打印按钮
var WF_DocUnid = $("#WF_DocUnid").val(); //
var newWindow; 
var OpenWindow;
function draftPrint(WF_DocUnid){//草稿打印
    var url = "https://api.oumeng.com.cn/ureport/preview?_u=file:%E6%97%A5%E5%B8%B8%E8%B4%B9%E7%94%A8%E6%8A%A5%E9%94%80%E5%8D%95.ureport.xml&_t=1,4,9&unid=" + $("#WF_DocUnid").val();
    window.open(url); 
}
function currentPrint(WF_DocUnid){//打印
    var url = "https://192.168.13.170/birtreport/frameset?__report=expense_fin.rptdesign&docNo="+$("#WF_DocUnid").val();
    window.open(url); 
}
function exportExcel(WF_DocUnid)  {//导出明细
    window.open('r?wf_num=R_finance_B047&DocUnid='+$("#WF_DocUnid").val());
}
function readTravelNo(WF_DocUnid){//预览出差计划单
    var travelId;
    if($("#WF_CurrentNodeid").val() == 'T10002' || $("#WF_CurrentNodeid").val()=='T10024'){
        travelId = $("#TravelNo").combobox('getValue');
    }else{
        //travelId = $("span#TravelNo").text();
        jQuery.ajax({
    	  type:"post",
          async:false,
          url:"rule?wf_num=R_finance_B063&WF_DocUnid=" + $("#WF_DocUnid").val(),
          dataType:"text", 
          data:{},
          success:function(data){
                travelId = data.trim();
          }
    	});
    }
    if(travelId == ""){
        alert("请选择出差计划单！");
        return;
    }else{
       var travelNoUrl = "rule?wf_num=R_S003_B062&wf_docunid=" + travelId;
        OpenUrl(travelNoUrl); 
    }
    
}
var isSave=false;
function formonload(){
    //隐藏处理框------20180704黄轶
    $("#UserTr_Node0").hide();
    
    /*//关联客户信息收集-----20180607黄轶
    var a;
    $("#travelTotal").attr('readonly','readonly');
    jQuery.ajax({
	  type:"post",
      async:false,
      url:"rule?wf_num=R_BasicData_B020",
      dataType:"text", 
      data:{},
      success:function(data){
            a = data.trim();
      }
	});
	if(a=="N"){
	    alert("您有客户人员信息收集工单未完成，暂时无法报销！");
	}*/
    
    
    var isRead = $("#comCode")[0].tagName.toLocaleLowerCase();
    //span标签为只读状态，不加载事件
    if(isRead!="span"){
        //表单打开，加载combobox数据（For Copy启动的流程）
        var userid=$("#staff_id").val();//凭证
        initInfos(userid);
    }
    var WF_DocStatus = $("#WF_DocStatus").val();//单据状态 Draft Current ARC
    if(WF_DocStatus == 'Draft'){
        $('#currentPrint').hide();
        $('#draftPrint').show();
    }else{
       $('#currentPrint').show();
       $('#draftPrint').hide(); 
    }
    
   // 接口财务审批环节显示凭证按钮id='WF_Processid' value='24a043ae0458d04ea80ab8d0e75c11ed4c46'凭证接口
    if(($("#WF_CurrentNodeid").val()=='T10024' || $("#WF_CurrentNodeid").val()=='T10009') && $("#WF_Processid").val()=='24a043ae0458d04ea80ab8d0e75c11ed4c46'){
         $('#checkproof').show();
    }else{
          $('#checkproof').hide();
    }
    //新建，只有新流程才可以编辑
    var newdoc = $("#WF_NewDocFlag").val();
    if((newdoc=="false" && $("#WF_IsFirstNodeFlag").val()=='false') ||$("#WF_DocStatus").val()=='ARC'||$('#WF_CurrentNodeid').val()=='T10024'){//新增财务一级审批节点凭证接口||
      var  doctype=$("#doctype").html(); 
      var doctypeFIn=$("#doctype").val();
        if(doctype=='日常报销'||doctypeFIn=='fin_daily'){//凭证接口
 	         $("#title").text("日 常 费 用 报 销 单 (员工）");
 	         $("#title1").text("Daily Expenses Reimbursement Form");
             $("#fin_day").show();  //fin_travel
 	         $("#fin_travel").hide(); 
            }else if(doctype=='境内差旅报销'||doctypeFIn=='fin_travel_domestic') {//凭证接口
                $('#controlDiv').show();
                var uid=$("#WF_DocUnid").val();
                if($('#WF_CurrentNodeid').val()=='T10024'){//凭证接口
                  $('#dc').datagrid({
                title:"填写出差天数，日期及出发地" ,
                singleSelect:false,
              // collapsible:true,
                method:'get',
                autoRowHeight:true,
                fitColumns:true,
                 rownumbers:true,
                url:'rule?wf_num=R_finance_B022&DocUnid='+uid,
                queryParams:{
                },
                columns:[[
                    {title:'序号',field:'icon',width:30,sortable:false,checkbox:($("#WF_ReadOnly").val()!='true')?true:false},
                    {title:'主键',field:'WF_OrUnid',hidden:true,sortable:false},
                    {title:'出差天数',field:'travel_days',width:100,sortable:true, editor:{
                        type:'numberbox',
                        precision:2,
                        options:{
                          required: false,
                            width:50
                        }
                    }},
                    {title:'开始时间',field:'sdate',width:100,sortable:true,editor:{
                        type:'datebox',
                        options:{
                            required: false,
                            showSeconds: false   
                        }
                    }},
                    {title:'结束时间',field:'edate',width:100,sortable:true,editor:{
                        type:'datebox',
                        options:{
                            required: false,
                        }
                    }},
                    {title:'出发地',field:'departure',width:100,sortable:true,
                    editor:{
                      type:'textarea',
                        options:{
                            required: false,
                            width:50
                        }
                    }},
                    {title:'目的地',field:'destination',width:100,sortable:true,editor:{
                        type:'textarea',
                        options:{
                            required: false,
                            width:50
                        }
                    }},
                     {title:'途径地',field:'bywayof',width:100,sortable:true,editor:{
                        type:'textarea',
                        options:{
                            required: false,
                            width:50
                        }
                    }},
                     {title:'出差事由',field:'reasons',width:100,sortable:true,editor:{
                        type:'textarea',
                        options:{
                            required: false,
                            width:50
                        }
                    }}
               
                ]],
                    onAfterEdit: function (rowIndex, rowData, changes) {//在添加完毕endEdit，保存时触发
                        editFlag = undefined;//重置
                        
                    },
                    onDblClickCell: function (rowIndex, field, value) {//双击该行修改内容
                   
                        if (editFlag != undefined) {
                           
                            $("#dc").datagrid('endEdit', editFlag);//结束编辑，传入之前编辑的行
                        }
                        if (editFlag == undefined) {
                           
                            $("#dc").datagrid('beginEdit', rowIndex);//开启编辑并传入要编辑的行
                          
                            editFlag = rowIndex;
                        }
                    }
            }); 
        if ($("#WF_ReadOnly").val()!='true'|| $('#WF_CurrentNodeid').val()=='T10024') {//凭证接口
          $('#dc').datagrid({
            toolbar: [{//在dategrid表单的头部添加按钮
                    text: "新增",
                    iconCls: "icon-add",
                     handler: function () {
                        if (editFlag != undefined) {
                            $("#dc").datagrid('endEdit', editFlag);//结束编辑，传入之前编辑的行
                        }
                        if (editFlag == undefined) {//防止同时打开过多添加行
                            $("#dc").datagrid('appendRow', {//在指定行添加数据，appendRow是在最后一行添加数据//insertRow
                              index: 0,    // 行数从0开始计算
                                row: {
                                   
                                    travel_days: '',
                                    sdate: '',
                                    edate:''
                                }
                            });
                            $("#dc").datagrid('beginEdit', 0);//开启编辑并传入要编辑的行
                            editFlag = 0;
                        }
                    
                     }
                  
                }, '-', {//'-'
                    text: "删除",
                    iconCls: "icon-remove",
                    handler: function () {
                        //选中要删除的行
                        var rows = $("#dc").datagrid('getSelections');
                        if (rows.length > 0) {//选中几行的话触发事件
                            $.messager.confirm("提示", "您确定要删除这些数据吗？一旦删除，无法撤销。", function (res) {//提示是否删除
                                if (res) {
                                  // var codes = new Array()
                                    for (var i = 0; i < rows.length; i++) {
                                    //    codes.push(rows[i].wf_orunid);
                                    var index = $("#dc").datagrid('getRowIndex', rows[i]);
                                        $("#dc").datagrid('deleteRow', index);
                                    }
                                }
                            });
                        }
                    }
                }, 
                //增加保存
                        {//'-'
                            text: "保存编辑",
                            iconCls: "icon-save",
                            handler: function () {
                              stopEditRow1(); 
                            }
                        }, 
               
                
                {
                    text: "撤销",
                    iconCls: "icon-redo",
                    handler: function () {
                        if (editFlag!=undefined) {
                            $("#dc").datagrid('rejectChanges');
                            editFlag = undefined;
                        }
                    }
                }, '-']
          });
    }  
                }else{
                $('#dc').datagrid({
                    title:"填写出差天数，日期及出发地" ,
                    singleSelect:false,
                    method:'get',
                    autoRowHeight:true,
                    fitColumns:true,
                     rownumbers:true,
                    url:'rule?wf_num=R_finance_B022&DocUnid='+uid,
                    queryParams:{
                    },
                    columns:[[
                        {title:'序号',field:'icon',width:30,sortable:false,checkbox:($("#WF_ReadOnly").val()!='true')?true:false},
                        {title:'主键',field:'WF_OrUnid',hidden:true,sortable:false},
                      
                        {title:'出差天数',field:'travel_days',width:100,sortable:true},
                        {title:'开始时间',field:'sdate',width:100,sortable:true},
                        {title:'结束时间',field:'edate',width:100,sortable:true},
                        {title:'出发地',field:'departure',width:100,sortable:true},
                        {title:'目的地',field:'destination',width:100,sortable:true},
                         {title:'途径地',field:'bywayof',width:100,sortable:true},
                         {title:'出差事由',field:'reasons',width:100,sortable:true}
                   
                    ]],
                        onAfterEdit: function (rowIndex, rowData, changes) {//在添加完毕endEdit，保存时触发
                            editFlag = undefined;//重置
                            
                        },
                        onDblClickCell: function (rowIndex, field, value) {//双击该行修改内容
                      
                            if (editFlag != undefined) {
                                $("#dc").datagrid('endEdit', editFlag);//结束编辑，传入之前编辑的行
                            }
                            if (editFlag == undefined) {
                                $("#dc").datagrid('beginEdit', rowIndex);//开启编辑并传入要编辑的行
                                editFlag = rowIndex;
                            }
                        }
                     }); }//凭证接口
                 $("#title").text("境 内 差 旅 费 用 报 销 单 (员工）");
     	         $("#title1").text("Domestic Travel Expense Reimbursement Form");
                 $("#fin_day").hide();  //fin_travel
     	         $("#fin_travel").show(); 
            }else{
                 $("#title").text("境 外 差 旅 费 用 报 销 单 (员工）");
     	         $("#title1").text("Oversea Travel Expense Reimbursement Form");
                 $("#fin_day").hide();  //fin_travel
     	         $("#fin_travel").show(); 
                 //增加编辑表格
                    var uid=$("#WF_DocUnid").val();
                    if($('#WF_CurrentNodeid').val()=='T10024'){//凭证接口
                       $('#dc').datagrid({
                title:"填写出差天数，日期及出发地" ,
                singleSelect:false,
              // collapsible:true,
                method:'get',
                autoRowHeight:true,
                fitColumns:true,
                 rownumbers:true,
                url:'rule?wf_num=R_finance_B022&DocUnid='+uid,
                queryParams:{
                   
                },
                columns:[[
                    {title:'序号',field:'icon',width:30,sortable:false,checkbox:($("#WF_ReadOnly").val()!='true')?true:false},
                    {title:'主键',field:'WF_OrUnid',hidden:true,sortable:false},
                    {title:'出差天数',field:'travel_days',width:100,sortable:true, editor:{
                        type:'numberbox',
                        precision:2,
                        options:{
                          required: false,
                            width:50
                        }
                    }},
                    {title:'开始时间',field:'sdate',width:100,sortable:true,editor:{
                        type:'datebox',
                        options:{
                            required: false,
                            showSeconds: false   
                        }
                    }},
                    {title:'结束时间',field:'edate',width:100,sortable:true,editor:{
                        type:'datebox',
                        options:{
                            required: false,
                        }
                    }},
                    {title:'出发地',field:'departure',width:100,sortable:true,
                    editor:{
                       
                      type:'textarea',
                        options:{
                            required: false,
                            width:50
                        }
                    }},
                    {title:'目的地',field:'destination',width:100,sortable:true,editor:{
                        type:'textarea',
                        options:{
                            required: false,
                            width:50
                        }
                    }},
                     {title:'途径地',field:'bywayof',width:100,sortable:true,editor:{
                        type:'textarea',
                        options:{
                            required: false,
                            width:50
                        }
                    }},
                     {title:'出差事由',field:'reasons',width:100,sortable:true,editor:{
                        type:'textarea',
                        options:{
                            required: false,
                            width:50
                        }
                    }}
               
                ]],
                    onAfterEdit: function (rowIndex, rowData, changes) {//在添加完毕endEdit，保存时触发
                        editFlag = undefined;//重置
                        
                    },
                    onDblClickCell: function (rowIndex, field, value) {//双击该行修改内容
                   
                        if (editFlag != undefined) {
                           
                            $("#dc").datagrid('endEdit', editFlag);//结束编辑，传入之前编辑的行
                        }
                        if (editFlag == undefined) {
                           
                            $("#dc").datagrid('beginEdit', rowIndex);//开启编辑并传入要编辑的行
                          
                            editFlag = rowIndex;
                        }
                    }
            }); 
        if ($("#WF_ReadOnly").val()!='true'|| $('#WF_CurrentNodeid').val()=='T10024') {//凭证接口
          $('#dc').datagrid({
            toolbar: [{//在dategrid表单的头部添加按钮
                    text: "新增",
                    iconCls: "icon-add",
                     handler: function () {
                        if (editFlag != undefined) {
                            $("#dc").datagrid('endEdit', editFlag);//结束编辑，传入之前编辑的行
                        }
                        if (editFlag == undefined) {//防止同时打开过多添加行
                            $("#dc").datagrid('appendRow', {//在指定行添加数据，appendRow是在最后一行添加数据//insertRow
                              index: 0,    // 行数从0开始计算
                                row: {
                                   
                                    travel_days: '',
                                    sdate: '',
                                    edate:''
                                }
                            });
                            $("#dc").datagrid('beginEdit', 0);//开启编辑并传入要编辑的行
                            editFlag = 0;
                        }
                    
                     }
                  
                }, '-', {//'-'
                    text: "删除",
                    iconCls: "icon-remove",
                    handler: function () {
                        //选中要删除的行
                        var rows = $("#dc").datagrid('getSelections');
                        if (rows.length > 0) {//选中几行的话触发事件
                            $.messager.confirm("提示", "您确定要删除这些数据吗？一旦删除，无法撤销。", function (res) {//提示是否删除
                                if (res) {
                                  // var codes = new Array()
                                    for (var i = 0; i < rows.length; i++) {
                                    //    codes.push(rows[i].wf_orunid);
                                    var index = $("#dc").datagrid('getRowIndex', rows[i]);
                                        $("#dc").datagrid('deleteRow', index);
                                    }
                                }
                            });
                        }
                    }
                }, 
                //增加保存
                        {//'-'
                            text: "保存编辑",
                            iconCls: "icon-save",
                            handler: function () {
                              stopEditRow1(); 
                            }
                        }, 
               
                
                {
                    text: "撤销",
                    iconCls: "icon-redo",
                    handler: function () {
                        if (editFlag!=undefined) {
                            $("#dc").datagrid('rejectChanges');
                            editFlag = undefined;
                        }
                    }
                }, '-']
          });
    } 
                    }else{//凭证接口
                   $('#dc').datagrid({
                    title:"填写出差天数，日期及出发地" ,
                    singleSelect:false,
                  // collapsible:true,
                    method:'get',
                    autoRowHeight:true,
                    fitColumns:true,
                     rownumbers:true,
                    //url:'r',
                    url:'rule?wf_num=R_finance_B022&DocUnid='+uid,
                    queryParams:{
                       
                    },
                    columns:[[
                        {title:'序号',field:'icon',width:30,sortable:false,checkbox:($("#WF_ReadOnly").val()!='true')?true:false},
                        {title:'主键',field:'WF_OrUnid',hidden:true,sortable:false},
                      
                        {title:'出差天数',field:'travel_days',width:100,sortable:true},
                        {title:'开始时间',field:'sdate',width:100,sortable:true},
                        {title:'结束时间',field:'edate',width:100,sortable:true},
                        {title:'出发地',field:'departure',width:100,sortable:true},
                        {title:'目的地',field:'destination',width:100,sortable:true},
                        {title:'途径地',field:'bywayof',width:100,sortable:true},
                        {title:'出差事由',field:'reasons',width:100,sortable:true}
                    ]],
                        onAfterEdit: function (rowIndex, rowData, changes) {//在添加完毕endEdit，保存时触发
                            editFlag = undefined;//重置
                        },
                        onDblClickCell: function (rowIndex, field, value) {//双击该行修改内容
                            if (editFlag != undefined) {
                                $("#dc").datagrid('endEdit', editFlag);//结束编辑，传入之前编辑的行
                            }
                            if (editFlag == undefined) {
                                $("#dc").datagrid('beginEdit', rowIndex);//开启编辑并传入要编辑的行
                                editFlag = rowIndex;
                            }
                        }
                }); }
        }
        $('input:radio[name=Reply]').each(function(index,domEle){
            $(this).attr("disabled", "disabled"); 
        });
    }
    //判断为驳回状态
     if((newdoc=="false" && $("#WF_IsFirstNodeFlag").val()=='true')||$("#WF_DocStatus").val()=='ARC'||$("#WF_DocStatus").val()=='Draft'){
        var doctype=$("#doctype").combobox('getValue'); 
        if(doctype=='fin_daily'){
 	         $("#title").text("日 常 费 用 报 销 单 (员工）");
 	         $("#title1").text("Daily Expenses Reimbursement Form");
             $("#fin_day").show();  //fin_travel
 	         $("#fin_travel").hide(); 
        }else if(doctype=='fin_travel_domestic'){
             $('#controlDiv').show();
            var uid=$("#WF_DocUnid").val();
         $('#dc').datagrid({
                title:"填写出差天数，日期及出发地" ,
                singleSelect:false,
              // collapsible:true,
                method:'get',
                autoRowHeight:true,
                fitColumns:true,
                 rownumbers:true,
                url:'rule?wf_num=R_finance_B022&DocUnid='+uid,
                queryParams:{
                   
                },
                columns:[[
                    {title:'序号',field:'icon',width:30,sortable:false,checkbox:($("#WF_ReadOnly").val()!='true')?true:false},
                    {title:'主键',field:'WF_OrUnid',hidden:true,sortable:false},
                    {title:'出差天数',field:'travel_days',width:100,sortable:true, editor:{
                        type:'numberbox',
                        precision:2,
                        options:{
                          required: false,
                            width:50
                        }
                    }},
                    {title:'开始时间',field:'sdate',width:100,sortable:true,editor:{
                        type:'datebox',
                        options:{
                            required: false,
                            showSeconds: false   
                        }
                    }},
                    {title:'结束时间',field:'edate',width:100,sortable:true,editor:{
                        type:'datebox',
                        options:{
                            required: false,
                        }
                    }},
                    {title:'出发地',field:'departure',width:100,sortable:true,
                    editor:{
                       
                      type:'textarea',
                        options:{
                            required: false,
                            width:50
                        }
                    }},
                    {title:'目的地',field:'destination',width:100,sortable:true,editor:{
                        type:'textarea',
                        options:{
                            required: false,
                            width:50
                        }
                    }},
                     {title:'途径地',field:'bywayof',width:100,sortable:true,editor:{
                        type:'textarea',
                        options:{
                            required: false,
                            width:50
                        }
                    }},
                     {title:'出差事由',field:'reasons',width:100,sortable:true,editor:{
                        type:'textarea',
                        options:{
                            required: false,
                            width:50
                        }
                    }}
               
                ]],
                    onAfterEdit: function (rowIndex, rowData, changes) {//在添加完毕endEdit，保存时触发
                        editFlag = undefined;//重置
                        
                    },
                    onDblClickCell: function (rowIndex, field, value) {//双击该行修改内容
                   
                        if (editFlag != undefined) {
                           
                            $("#dc").datagrid('endEdit', editFlag);//结束编辑，传入之前编辑的行
                        }
                        if (editFlag == undefined) {
                           
                            $("#dc").datagrid('beginEdit', rowIndex);//开启编辑并传入要编辑的行
                          
                            editFlag = rowIndex;
                        }
                    }
            }); 
        if ($("#WF_ReadOnly").val()!='true'|| $('#WF_CurrentNodeid').val()=='T10024') {//凭证接口
          $('#dc').datagrid({
            toolbar: [{//在dategrid表单的头部添加按钮
                    text: "新增",
                    iconCls: "icon-add",
                     handler: function () {
                        if (editFlag != undefined) {
                            $("#dc").datagrid('endEdit', editFlag);//结束编辑，传入之前编辑的行
                        }
                        if (editFlag == undefined) {//防止同时打开过多添加行
                            $("#dc").datagrid('appendRow', {//在指定行添加数据，appendRow是在最后一行添加数据//insertRow
                              index: 0,    // 行数从0开始计算
                                row: {
                                   
                                    travel_days: '',
                                    sdate: '',
                                    edate:''
                                }
                            });
                            $("#dc").datagrid('beginEdit', 0);//开启编辑并传入要编辑的行
                            editFlag = 0;
                        }
                    
                     }
                  
                }, '-', {//'-'
                    text: "删除",
                    iconCls: "icon-remove",
                    handler: function () {
                        //选中要删除的行
                        var rows = $("#dc").datagrid('getSelections');
                        if (rows.length > 0) {//选中几行的话触发事件
                            $.messager.confirm("提示", "您确定要删除这些数据吗？一旦删除，无法撤销。", function (res) {//提示是否删除
                                if (res) {
                                  // var codes = new Array()
                                    for (var i = 0; i < rows.length; i++) {
                                    //    codes.push(rows[i].wf_orunid);
                                    var index = $("#dc").datagrid('getRowIndex', rows[i]);
                                        $("#dc").datagrid('deleteRow', index);
                                    }
                                }
                            });
                        }
                    }
                }, 
                //增加保存
                        {//'-'
                            text: "保存编辑",
                            iconCls: "icon-save",
                            handler: function () {
                              stopEditRow1(); 
                            }
                        }, 
               
                
                {
                    text: "撤销",
                    iconCls: "icon-redo",
                    handler: function () {
                        if (editFlag!=undefined) {
                            $("#dc").datagrid('rejectChanges');
                            editFlag = undefined;
                        }
                    }
                }, '-']
          });
    }
          $("#title").text("境 内 差 旅 费 用 报 销 单 (员工）");
          $("#title1").text("Domestic Travel Expense Reimbursement Form");                  
          $("#fin_day").hide();  //fin_travel
          $("#fin_travel").show(); 
        }else{
                 $("#title").text("境 外 差 旅 费 用 报 销 单 (员工）");
     	         $("#title1").text("Oversea Travel Expense Reimbursement Form");
                 $("#fin_day").hide();  //fin_travel
     	         $("#fin_travel").show(); 
                var uid=$("#WF_DocUnid").val();
                $('#dc').datagrid({
                    title:"填写出差天数，日期及出发地" ,
                    singleSelect:false,
                  // collapsible:true,
                    method:'get',
                    autoRowHeight:true,
                    fitColumns:true,
                     rownumbers:true,
                    url:'rule?wf_num=R_finance_B022&DocUnid='+uid,
                    queryParams:{
                    },
                    columns:[[
                        {title:'序号',field:'icon',width:30,sortable:false,checkbox:($("#WF_ReadOnly").val()!='true')?true:false},
                        {title:'主键',field:'WF_OrUnid',hidden:true,sortable:false},
                        {title:'出差天数',field:'travel_days',width:100,sortable:true, editor:{
                            type:'numberbox',
                            precision:2,
                            options:{
                              required: false,
                                width:50
                            }
                        }},
                        {title:'开始时间',field:'sdate',width:100,sortable:true,editor:{
                            type:'datebox',
                            options:{
                                required: false,
                                showSeconds: false   
                            }
                        }},
                        {title:'结束时间',field:'edate',width:100,sortable:true,editor:{
                            type:'datebox',
                            options:{
                                required: false,
                            }
                        }},
                        {title:'出发地',field:'departure',width:100,sortable:true,
                        editor:{
                           
                          type:'textarea',
                            options:{
                                required: false,
                                width:50
                            }
                        }},
                        {title:'目的地',field:'destination',width:100,sortable:true,editor:{
                            type:'textarea',
                            options:{
                                required: false,
                                width:50
                            }
                        }},
                         {title:'途径地',field:'bywayof',width:100,sortable:true,editor:{
                            type:'textarea',
                            options:{
                                required: false,
                                width:50
                            }
                        }},
                         {title:'出差事由',field:'reasons',width:100,sortable:true,editor:{
                            type:'textarea',
                            options:{
                                required: false,
                                width:50
                            }
                        }}
                   
                    ]],
                        onAfterEdit: function (rowIndex, rowData, changes) {//在添加完毕endEdit，保存时触发
                            editFlag = undefined;//重置
                            
                        },
                        onDblClickCell: function (rowIndex, field, value) {//双击该行修改内容
                            if (editFlag != undefined) {
                                $("#dc").datagrid('endEdit', editFlag);//结束编辑，传入之前编辑的行
                            }
                            if (editFlag == undefined) {
                                $("#dc").datagrid('beginEdit', rowIndex);//开启编辑并传入要编辑的行
                                editFlag = rowIndex;
                            }
                        }
                }); 
        if ($("#WF_ReadOnly").val()!='true' || $('#WF_CurrentNodeid').val()=='T10024') {//凭证接口
            $('#dc').datagrid({
            toolbar: [{//在dategrid表单的头部添加按钮
                text: "新增",
                iconCls: "icon-add",
                 handler: function () {
                    if (editFlag != undefined) {
                        $("#dc").datagrid('endEdit', editFlag);//结束编辑，传入之前编辑的行
                    }
                    if (editFlag == undefined) {//防止同时打开过多添加行
                        $("#dc").datagrid('appendRow', {//在指定行添加数据，appendRow是在最后一行添加数据//insertRow
                          index: 0,    // 行数从0开始计算
                            row: {
                               
                                travel_days: '',
                                sdate: '',
                                edate:''
                            }
                        });
                        $("#dc").datagrid('beginEdit', 0);//开启编辑并传入要编辑的行
                        editFlag = 0;
                    }
                
                 }
              
            }, '-', {//'-'
                text: "删除",
                iconCls: "icon-remove",
                handler: function () {
                    //选中要删除的行
                    var rows = $("#dc").datagrid('getSelections');
                    if (rows.length > 0) {//选中几行的话触发事件
                        $.messager.confirm("提示", "您确定要删除这些数据吗？一旦删除，无法撤销。", function (res) {//提示是否删除
                            if (res) {
                              // var codes = new Array()
                                for (var i = 0; i < rows.length; i++) {
                                //    codes.push(rows[i].wf_orunid);
                                var index = $("#dc").datagrid('getRowIndex', rows[i]);
                                    $("#dc").datagrid('deleteRow', index);
                                }
                            }
                        });
                    }
                }
            }, 
           //增加保存
                    {//'-'
                        text: "保存编辑",
                        iconCls: "icon-save",
                        handler: function () {
                          stopEditRow1(); 
                        }
                    }, 
            
            {
                text: "撤销",
                iconCls: "icon-redo",
                handler: function () {
                    if (editFlag!=undefined) {
                        $("#dc").datagrid('rejectChanges');
                        editFlag = undefined;
                    }
                }
            }, '-']
      });
    }
        }
        $('input:radio[name=Reply]').each(function(index,domEle){
            $(this).attr("disabled", "disabled"); 
        });
        
       
    //驳回状态时合计等字段为不可编辑状态
     document.getElementById("text9").readOnly="readonly";
       document.getElementById("added_amount_tax").readOnly="readonly";//营改增
       
       document.getElementById("added_noamount_tax").readOnly="readonly";//
       document.getElementById("added_airamount_tax").readOnly="readonly";//
       document.getElementById("added_caramount_tax").readOnly="readonly";//
       document.getElementById("added_trainamount_tax").readOnly="readonly";//
       document.getElementById("added_eleamount_tax").readOnly="readonly";//
        //营改增VAT
        document.getElementById("Staff_comm_VAT").readOnly="readonly";
        document.getElementById("Business_traveling_VAT").readOnly="readonly";
        document.getElementById("Business_enter_VAT").readOnly="readonly";   
        document.getElementById("team_building_VAT").readOnly="readonly";
        document.getElementById("Overtime_Meal_VAT").readOnly="readonly";
        
        document.getElementById("employee_benefits_VAT").readOnly="readonly";
        document.getElementById("travel_visa_VAT").readOnly="readonly";
        document.getElementById("travel_other_VAT").readOnly="readonly";   
        document.getElementById("travel_accom_VAT").readOnly="readonly";
        document.getElementById("travel_meals_VAT").readOnly="readonly";   
         document.getElementById("travel_office_VAT").readOnly="readonly";
        document.getElementById("travel_air_ticket_VAT").readOnly="readonly";   
         document.getElementById("postage_VAT").readOnly="readonly"; //凭证
         document.getElementById("postage").readOnly="readonly"; //凭证
        //结束
        document.getElementById("text10").readOnly="readonly";
        
        document.getElementById("text13").readOnly="readonly";
        document.getElementById("text14").readOnly="readonly";   
        document.getElementById("text17").readOnly="readonly";
        document.getElementById("text18").readOnly="readonly";   
       
        document.getElementById("Business_traveling").readOnly="readonly";   
        document.getElementById("Staff_communication_expense").readOnly="readonly";
        document.getElementById("Business_entertainment").readOnly="readonly";  
        document.getElementById("team_building").readOnly="readonly";   
        document.getElementById("Overtime_Meal_Allowance").readOnly="readonly";
        document.getElementById("employee_benefits").readOnly="readonly";   
        
        document.getElementById("travel_visa_insurance").readOnly="readonly";   
        document.getElementById("travel_other_transportation").readOnly="readonly";
        document.getElementById("travel_accommodation").readOnly="readonly";   
        document.getElementById("travel_meals").readOnly="readonly";  
        document.getElementById("travel_communication").readOnly="readonly"; //2017-05-18  
        document.getElementById("travel_postage").readOnly="readonly";//王南修改 20180108
        document.getElementById("travel_office").readOnly="readonly";
        document.getElementById("travel_air_ticket").readOnly="readonly";   
        
}
    
}


//表单打开时按公司代码加载级联combobox
function initInfos(userid){
    $('#title').attr("disabled",false); 
    $('#title1').attr("disabled",false);
    var WF_DocUnid = $("#WF_DocUnid").val(); 
    $("#comCode").combobox({   
        url:"rule?wf_num=R_finance_B005&userid="+userid,
        valueField:'val', 
        textField:'text'
    });
    $('#cost_center').combobox({
        url:"rule?wf_num=R_finance_B004&userid="+userid+"&comCode="+$('#comCode').combobox('getValue'),
        valueField:'val',
        textField:'text'
    });
    //银行卡号
    $("#bank_A_C").combobox({   
        url:"rule?wf_num=R_finance_B023&userid="+userid,
        valueField:'val', 
        textField:'text'
    });
    //出差计划单，默认按照时间升序，离现在越远的越排在前面
    //document.getElementById('cCusCode').value=val.split(",")[1];
    $('#TravelNo').combobox({ 
    	url:"rule?wf_num=R_finance_B060&WF_DocUnid=" + WF_DocUnid,
    	valueField:'id',
    	textField:'text'
    }).combobox({"editable":false});
    
}

 var flag="";
 var aaa ; 
 var bbb;
 function formonsubmit(){
     debugger
    //alert("提交日常费用报销。。。");
    if($('#WF_CurrentNodeid').val()=='T10002'){
        var dType = $("#doctype").combobox('getValue');
        var travelNo = $("#TravelNo").combobox('getValue');
        if((dType == "fin_travel_domestic" || dType == "fin_travel_foreign") && travelNo == ""){
            alert("请选择出差计划单！");
            return false;
        }
    }
    
    /*//关联客户信息收集-----20180607黄轶
    if($('#WF_CurrentNodeid').val()=='T10002'){
        var a;
        jQuery.ajax({
    	  type:"post",
          async:false,
          url:"rule?wf_num=R_BasicData_B020",
          dataType:"text", 
          data:{},
          success:function(data){
                a = data.trim();
          }
    	});
    	if(a=="N"){
    	    alert("您有客户人员信息收集工单未完成，暂时无法报销！");
    	    return false;
    	}
    }*/
    
    
    if($("#WF_IsFirstNodeFlag").val()!='false' ||$('#WF_CurrentNodeid').val()=='T10024') {//凭证接口
        //  -------------------------------------------------验证表格数据--------------------------------------------------------------
        
        if(validateDetail().stat==1){
            alert(validateDetail().msg);
            return false;
        }
        computer0();
        if(!_validatePass){// 计算后数据验证失败
           return false; 
        }
        saveDetail();
        //Excel验证
        if(aaa){
         alert("文档保存错误,请核对数据是否正确！");
         return false;
        }
        doctype=$("#doctype").combobox('getValue');
        // alert("办理状态"+flag);
       if(flag=='1'){
    	var rows = $("#dg").datagrid('getRows');
    	if(doctype=='fin_daily'){
  	    	if(rows=="" || rows==null){
	        alert("表体没有数据,无法提交！");
	        return false;
	   }
  	} 
	    var rows = $("#dg").datagrid('getRows');
        for (var i = 0; i < rows.length; i++) {
        var str = rows[i]['budget_dept'];
     if($('#WF_CurrentNodeid').val()!='T10024'){//凭证接口
      //Excel导入验证
      var comCode=$('#comCode').combobox('getValue');
    //   var userid=$("#WF_UserName").val();
         var userid=$("#staff_id").val();//凭证
      var b = false;
      var c = false;
      var d=false;
        jQuery.ajax({
            type:"post",
            async:false,
            url:'rule?wf_num=R_finance_B006&userid='+userid+'&comCode='+comCode,
            dataType:"text",
            data:{
              
            },
            success:function(data){
              var models = eval("("+data+")");
              var rows="";
               var strbudget="";
                for(var x in models){
                 strbudget+=models[x].id;
                
                }
                // alert("str---"+str+"==strbudget"+strbudget);
                // if(strbudget.indexOf(str)>=0 && str.length==6)   
                 if(strbudget== str)   
                    {  
                    }  else{
                        b = true;
                    }
              }
        
          });
           var x=i+1
         if(b){
              alert("您第'"+x+"'行的预算部门编码不正确，请确认选择");
             return false;
             
         }
         
          if($("#doctype").combobox('getValue')=='fin_travel_foreign'||$("#doctype").combobox('getValue')=='fin_travel_domestic'){
            if(rows[i]['expenses_item'].indexOf("差旅")>=0){
               
            }else{
                c= true;
            }
             if(rows[i]['budget_item'].indexOf("差旅")>=0){
               
            }else{
                c= true;
            }
          }
         // alert($("#doctype").combobox('getValue'));
          if($("#doctype").combobox('getValue')=='fin_daily'){// 日常费用报销不会有差旅相关的费用类型
            if(rows[i]['expenses_item'].indexOf("差旅")>=0){
                d= true;
            }else{
               
            }
             if(rows[i]['budget_item'].indexOf("差旅")>=0){
                d= true;
            }else{
               
            }
            
          }
           if(c){
              alert("您的费用类别或预算项目输入不正确，差旅费报销必须填写和差旅相关的费用");
             return false;
             
         }
          if(d){
              alert("您的费用类别或预算项目输入不正确，日常报销必须填写和日常相关的费用");
             return false;
             
         }
        //结束
     }  
            //rows[i]['FX_rate']
            //验证费用类别与预算项目是否一致Excel导入验证
            //新的出来之后，此处不适用了，王南注释 20190510
        //  if(rows[i]['expenses_item'].indexOf(rows[i]['budget_item'])<0){
        //      alert("费用类别与预算项目不一致，请重新选择费用类别");
        //      return false;
        //  }
    	  if(rows[i]['budget_dept']==""){
    	      alert("预算部门不可以为空，请确认！");//departure
        	   return false; 
    	  }
    	  if(rows[i]['expenses_item']==""){
    	      alert("费用类别不可以为空，请确认！");//departure
        	   return false; 
    	  }
    	   if(rows[i]['budget_item']==""){
    	      alert("预算项目不可以为空，请确认！");//departure
        	   return false; 
    	  }
    	     if(rows[i]['date_fill']==""){
    	      alert("日期不可以为空，请确认！");//departure
        	   return false; 
    	  }
    	   if(rows[i]['currency']==""){
    	      alert("币种不可以为空，请确认！");//departure
        	   return false; 
    	  }
    	    if(rows[i]['FC_Amount']==""){
    	      alert("外币金额不可以为空，请确认！");//departure
        	   return false; 
    	  }
    	  //alert("=====" + rows[i]['if_tax']);
    	  //增值税-发票号必填
    	  if(rows[i]['if_tax'] == "增值税专用发票" || rows[i]['if_tax'] == "增值税电子普通发票(交通类)" || rows[i]['if_tax'] == "增值税普通发票(其他)"){
    	        if(rows[i]['invoice_number']==""){
    	            var x=i+1;
    	            alert("您第"+x+"行,必须填写发票号！");//departure
        	        return false;   
    	        }
    	    } 
    	  
        }
     
     }
	//提交调用
    if($("#doctype").combobox('getValue')=='fin_travel_foreign'||$("#doctype").combobox('getValue')=='fin_travel_domestic'){	
	GetEditorValList();
	 //保存出差
      var WF_DocUnid = $("#WF_DocUnid").val(); 
      var EditorValList=$("#EditorValList").val().replaceAll("'","").replaceAll("&"," ");
    //  alert("EditorValList:"+EditorValList);
        jQuery.ajax({
            type:"post",
            async:false,
            url:"rule?wf_num=R_finance_B021&DocUnid="+WF_DocUnid,//+"&EditorValList="+encodeURIComponent(EditorValList),
            dataType:"text",
            data:{
               EditorValList:EditorValList  
            },
            success:function(data){
               var d = eval("("+data+")");
                if(d.success){//Excel
                    
                    bbb= false;
                }else{
                    bbb = true;
                }
              }
        
          }); 		
  	   }	
 
  if(bbb){
         alert("文档保存错误,请核对数据是否正确！");
         return false;
     }
  	//修改流程名称
  	if ($("#Subject").val()=='' || $("#Subject").val()=='财务报销' || $("#Subject").val()=='日常费用报销') {
        $("#Subject").val($("#staff_name").val()+$("#appl_date").datebox('getValue')+$("#WF_ProcessName").val());
    }
    //关联出差计划单，比较总金额，差额备注必填 王南增加 20180507
    var travelTotal = document.getElementById('travelTotal').value;
    var text9Total = document.getElementById('text9').value;
    var travelRemark = document.getElementById('travelRemark').value;
    
    //若报销金额大于此计划单金额（非公司定机票金额之和），则在报销单中填写【“超出差计划单”金额原因】，并红色字体显示
    if(parseFloat(text9Total) > parseFloat(travelTotal) && travelRemark == ""){
        alert("报销金额大于出差计划单金额,请填写【“超出出差计划单”金额原因】！");
        return false;
    }
    
  }
  
}
//暂存办理
function GoToSaveDoc(){
      flag="2";
     computer0();
     if(_validatePass){// 计算结束后验证通过
          $("#WF_Remark").val($("#WF_TmpRemark").val());
    	  var formData=$("form").serialize();
    	  var checkBoxData=getNoCheckedBoxValue();
    	  if(checkBoxData!=""){formData+="&"+checkBoxData;}
    	  var textShowStr=getFieldTextShowData();
    	  if(textShowStr!=""){formData+="&"+textShowStr;} //_show字段的内容
    	  var r=formonsubmit();
    	  //alert("===="+typeof(r));
    	  if(typeof(r)=="boolean" && r==false){return;}
    	  else if(typeof(r) == "string"){formData+="&"+r;} //如果返回的时字符串则作为提交的附加数据
    	  var url="r?wf_num=R_S003_B031";
    	  if(!confirm("您确认要暂存文档吗?")){return false;}
    	  mask();
    	  $.post(url,formData,function(data){unmask();});
          window.parent.$('#tree').tree('reload'); 
     }
}
//办理完成
function GoToNextNode(){ 
      flag="1";
	//提交到下一环节
	var NodeList=""; //获得选中的节点
	$('input[name="WF_NextNodeSelect"]:checked').each(function(){
		if(NodeList==""){NodeList=$(this).val();}
		else{NodeList+=","+$(this).val();}
	});
	if($('input[name="WF_NextNodeSelect"]').length>0){ //看是否可以选择环节
		if(NodeList==""){alert("请选择一个环节再提交!");return false;}
		//获得审批用户列表
		var UserList="";
		var NodeArray=NodeList.split(",");
		for(var i=0;i<NodeArray.length;i++)
		{
			var Nodeid=NodeArray[i];
			var obj=$("#WF_"+Nodeid);
			if(obj.length>0)
			{
				var NodeName=obj.attr("NodeName");
				var MaxUserNum=obj.attr("MaxUserNum")-0;
				var MinUserNum=obj.attr("MinUserNum")-0;
				var userList=obj.val()+"";
				var UserArray=userList.split(",");
				if(UserArray.length>MaxUserNum && MaxUserNum!=0){alert("环节("+NodeName+")超出最大可选参与人数!");return false;}
				if((userList=="null" || userList=="") && MinUserNum!=0)
				{
					alert("环节("+NodeName+")没有指定任务处理人!");
					return false;
				}
				if(UserArray.length<MinUserNum){alert("环节("+NodeName+")少于最小参与人数!"); return false;}
				for(var j=0;j<UserArray.length;j++)
				{
					if(UserArray[j]!=""){
						if(UserList==""){UserList=UserArray[j]+"$"+Nodeid;}else{UserList+=","+UserArray[j]+"$"+Nodeid;}
					}
				}
			}
		}
		$("#WF_NextNodeid").val(NodeList);
		$("#WF_NextUserList").val(UserList);
	}
	SaveDocument("EndUserTask","您确认要提交本流程吗?");
}
//凭证接口
//WF_Action为引擎动作id,WF_Params为post时的附加参数,msg为提示消息
function SaveDocument(WF_Action,msg,WF_Params){
	if(WF_Action==undefined || WF_Action==""){WF_Action="EndUserTask";}
 	if(GetRemarkStr()==false){return;}
	var formData="";
	var checkBoxData=getNoCheckedBoxValue();
	if(checkBoxData!=""){formData=checkBoxData;} //单选复选框提交
	var textShowStr=getFieldTextShowData();
	if(textShowStr!=""){formData+="&"+textShowStr;} //_show字段的内容
	if(WF_Action){formData+="&WF_Action="+WF_Action;} //要提交的动作，默认为EndUserTask办理完成
	formData+="&WF_CopyUserList="+encodeURIComponent($("#WF_SelCopyUser").val()); //要抄送的用户列表
	if($("#WF_SelSendSms").val()!=undefined){
		formData+="&WF_SendSms="+$("#WF_SelSendSms").val();  //1表示手机短信发送标记
	}
	if(WF_Params!=undefined && WF_Params!=""){
		formData+="&"+WF_Params; //传入的附加post参数,传入的WF_Params要进行utf-8编码
	}
	//alert("开始表单验证");
	//开始表单验证
	var isValid = $("#linkeyform").form('validate');
	if (isValid){
		var r=formonsubmit();
		if(typeof(r)=="boolean" && r==false){return;}
		else if(typeof(r) == "string"){formData+="&"+r;} //如果返回的时字符串则作为提交的附加数据
		r=validReadFieldIsNull();
		if(r==false){return false;} //检测只读的字段是否有必填选项
 	}else{
		alert("表单验证未通过,请检查表单数据后再次提交!");return;
 	}
	//序列号表单字段
	formData+="&"+$("#linkeyform").serialize();
	//显示提示消息
	if(msg!="" && msg!=undefined){if(!confirm(msg)){return false;}}
	//凭证接口
	mask();
	var url="r?wf_num=R_S003_B035";
	$.post(url,formData,function(data){
    		unmask();
    		var rs = eval('(' + data + ')');
			if(isMobile()){alert(rs.msg);location.replace("r?wf_num=P_S023_004");
			}else{
			    //alert("进入回调函数中。。。");
			    SaveDocumentCallBack(WF_Action,rs);
			    
			}
  	});
}
//获取编辑表格所有值,
function GetEditorValList(){
    var rows = $("#dc").datagrid('getRows');
	var val="";
	var v = "";
	var valList = "";
	var fdList = "travel_days,sdate,edate,departure,destination,bywayof,reasons"; //编辑表格所有可编辑字段
	var fdArray = fdList.split(","); //分隔数组分别取值
	$.each(rows, function (i, row) {
	    val="";
	    for(j=0;j<fdArray.length;j++){
	        v = eval("row."+fdArray[j]);
	            if(typeof(v) == "undefined"){
	                 if(fdArray[j]=="travel_days"){
	                    v=0; 
	                 }else{
	                v = "";
	                 }
	            }
	        val = val +"<"+fdArray[j]+">"+v+"</"+fdArray[j]+">";
	    }
		//累加编辑表格值
		valList = valList+"<attrbute>"+val+"</attrbute>";
	});
	var xmlValList = "<editinfo>"+valList+"</editinfo>";
	$("#EditorValList").val(xmlValList);
	//alert("999==="+xmlValList);
}
//新增加获取报销单中详细编辑表格
//2016-03-29获取编辑表格所有值,
function GetEditorValListFIN(){
  // stopEditRow1();
    var rows = $("#dg").datagrid('getRows');
	var val="";
	var v = "";
	var valList = "";
	var fdList = "date_fill,description,currency,FC_Amount,FX_rate,if_tax,Amount,tax_amount,invoice_code,invoice_number,is_budget,budget_dept,expenses_item,budget_item,invoices,riseCol"; //编辑表格所有可编辑字段   营改增
	var fdArray = fdList.split(","); //分隔数组分别取值
	$.each(rows, function (i, row) {
	    val="";
	    for(j=0;j<fdArray.length;j++){
	        v = eval("row."+fdArray[j]);
	      val = val +"<"+fdArray[j]+">"+v+"</"+fdArray[j]+">";
	    }
		//累加编辑表格值
		valList = valList+"<attrbute>"+val+"</attrbute>";
	});
	var xmlValList = "<editinfo>"+valList+"</editinfo>";
	$("#EditorValList").val(xmlValList);
}
function isEmpty(val){
    if(val=='' || val == null || val ==undefined || val=='undefined'){
        return true;
    }
    return false;
}
// 验证详细列表数据是否合法
function validateDetail(){
    stopEditRow();
    var item = $('#dg').datagrid('getRows');
    if(item.length <= 0){
        return {stat:1,msg:'报销列表不能为空！'}
    }
    var params = ['date_fill','description','Amount','expenses_item','if_tax','budget_item','budget_dept'];
    var value = ['日期','描述信息','人民币金额','费用类别','发票类型','预算项目','预算部门'];
    var _value = '';
    for(var i=0; i < item.length; i++){
        var date_fill = item[i].date_fill;
        var description = item[i].description;
        var amount = item[i].Amount;
        var expenses_item = item[i].expenses_item;
        var if_tax = item[i].if_tax;
        var budget_item = item[i].budget_item;
        var budget_dept = item[i].budget_dept;
        if(isEmpty(date_fill)){// 日期
            return {stat:1,msg:"发票报销数据中第"+(i+1)+ "行[" + value[0] + "]不能为空！"}
        }
        if(isEmpty(description)){// 描述信息
            return {stat:1,msg:"发票报销数据中第"+(i+1)+ "行[" + value[1] + "]不能为空！"}
        }
        if(isEmpty(if_tax)){// 发票类型
            return {stat:1,msg:"发票报销数据中第"+(i+1)+ "行[" + value[4] + "]不能为空！"}
        }
        if(amount=='' || amount <= 0 || amount =='0.00' || amount=='0.0'){ // 人民币金额
                return {stat:1,msg:'发票报销数据中人民币金额必须大于0！'}
        }
        if(isEmpty(budget_dept)){// 预算部门
            return {stat:1,msg:"发票报销数据中第"+(i+1)+ "行[" + value[6] + "]不能为空！"}
        }
        if(isEmpty(expenses_item)){// 发票类型
            return {stat:1,msg:"发票报销数据中第"+(i+1)+ "行[" + value[3] + "]不能为空！"}
        }
        if(isEmpty(budget_item)){// 预算项目
            return {stat:1,msg:"发票报销数据中第"+(i+1)+ "行[" + value[5] + "]不能为空！"}
        }
    }
    return {stat:0,msg:'success'}
}
//2016-03-29保存报销单编辑表格的明细表
function saveDetail(){
	GetEditorValListFIN();
	 //保存编辑表格明细
      var WF_DocUnid = $("#WF_DocUnid").val(); 
      //var EditorValList=$("#EditorValList").val();
        var EditorValList=$("#EditorValList").val().replaceAll("'","").replaceAll("&"," ");
    //  alert("EditorValList:"+EditorValList);
        jQuery.ajax({
            type:"post",
            async:false,
           
            url:"rule?wf_num=R_finance_B036&DocUnid="+WF_DocUnid,
            dataType:"text",
            data:{
               EditorValList:EditorValList 
            },//Excel验证   
            success:function(data){
                var d = eval("("+data+")");
                if(d.success){
                    aaa= false;
                }else{
                    aaa = true;
                }
              }
        
          }); 		
}

function stopEditRow1(){
	$('#dc').datagrid('endEdit', editFlag);
	editFlag=undefined;
}

// 判断计算的数据是否合法
function _validateLegal(params,header){
    var s=0;// 方法状态
    var m='success'; // 方法消息
    if('NaN' == params){
        s=1;
        m="计算出错["+header+':NaN]';
    }else if('数据非法' == params){
        s=1;
        m="计算出错["+header+':数据非法]';
    }else if('undefined' == params){
        s=1;
        m="计算出错["+header+':undefined]';
    }
    return {stat:s,msg:m};
}

// 前台验证计算后的数据是否合法（用于computer0()方法计算后）
function _validateParams(){
    
    // _params与_value一一对应
    var _params = ['text9','added_airamount_tax','added_airamount','text12','added_caramount_tax','added_caramount','text13','added_trainamount_tax','added_trainamount'
                 ,'text14','added_eleamount_tax','added_eleamount','added_amount_tax','added_noamount_tax'
                 ,'Business_traveling','Business_traveling_VAT','Staff_communication_expense','Staff_comm_VAT','Business_entertainment','Business_enter_VAT'
                 ,'team_building','team_building_VAT','Overtime_Meal_Allowance','Overtime_Meal_VAT','employee_benefits','employee_benefits_VAT'
                 ,'travel_visa_insurance','travel_visa_VAT','travel_other_transportation','travel_other_VAT','travel_accommodation','travel_accom_VAT','travel_meals'
                 ,'travel_meals_VAT','travel_office','travel_office_VAT','travel_air_ticket'
                 ,'travel_air_ticket_VAT','travel_communication','travel_postage','postage','postage_VAT','text10','text16','text17','text18'];
    var _value = ['合计（小写）','可抵扣机票(可抵扣)税额','可抵扣机票(可抵扣)税额','减：公司预付款','可抵扣汽车票+船票(实名)税额','可抵扣汽车票+船票(实名)税额','应付合计（小写）','可抵扣火车票(实名)税额','可抵扣火车票(实名)税额'
                 ,'应退回公司合计（小写）','可抵扣火车票(实名)税额','可抵扣火车票(实名)税额','可抵扣增值税金额','可抵扣非增值税金额'
                 ,'市内交通费','市内交通费VAT','员工通讯费','员工通讯费VAT','业务招待费','业务招待费VAT'
                 ,'团队建设','团队建设VAT','误餐费','误餐费VAT','职工福利','职工福利VAT'
                 ,'差旅费_签证和保险','差旅费_签证和保险VAT','差旅费_其他交通费','差旅费_其他交通费VAT','差旅费_住宿费','差旅费_住宿费VAT','差旅费_餐费'
                 ,'差旅费_餐费VAT','差旅费_办公费','差旅费_办公费VAT','差旅费_机票'
                 ,'差旅费_机票VAT','差旅费_员工通讯费','差旅费_邮寄费','邮寄费','邮寄费VAT','合计（小写）','减：公司预付款','应付合计（小写）','应退回公司合计（小写）'];
    var _val = "";
    for(var i=0; i<_params.length;i++){
        _val = $("#" + _params[i]).val();
        var _res = _validateLegal(_val,_value[i]);
        if(_res.stat == 1){
            return {stat:1,msg:_res.msg};
        }
    }
     return {stat:0,msg:'success'};
}
function handleParams(){
    var _params = ['text9','added_airamount_tax','added_airamount','text12','added_caramount_tax','added_caramount','text13','added_trainamount_tax','added_trainamount'
                 ,'text14','added_eleamount_tax','added_eleamount','added_amount_tax','added_noamount_tax'
                 ,'Business_traveling','Business_traveling_VAT','Staff_communication_expense','Staff_comm_VAT','Business_entertainment','Business_enter_VAT'
                 ,'team_building','team_building_VAT','Overtime_Meal_Allowance','Overtime_Meal_VAT','employee_benefits','employee_benefits_VAT'
                 ,'travel_visa_insurance','travel_visa_VAT','travel_other_transportation','travel_other_VAT','travel_accommodation','travel_accom_VAT','travel_meals'
                 ,'travel_meals_VAT','travel_office','travel_office_VAT','travel_air_ticket'
                 ,'travel_air_ticket_VAT','travel_communication','travel_postage','postage','postage_VAT','text10','text16','text17','text18'];
    var _val = "";
    var v = "";
    for(var i=0; i<_params.length; i++){
        v = $("#" + _params[i]).val();
        _val += "<"+_params[i]+">"+v+"</"+_params[i]+">";
    }
    var valList = "<attrbute>"+_val+"</attrbute>";
    var xmlValList = "<editinfo>"+valList+"</editinfo>";
	$("#valValList").val(xmlValList);
}
// 后台验证计算后的数据是否合法（用于computer0()方法计算后）
function validateParams(){
    handleParams();
    var valValList=$("#valValList").val();
    if(valValList=='' || valValList == null || valValList == 'null' || valValList ==undefined || valValList=='undefined'){
       console.log('验证数据：报销单据列表为空，请先手动添加或者导入数据！');
       return {stat:0,msg:'报销单据列表为空，请先手动添加或者导入数据！'}; 
    }else{
        valValList=valValList.replaceAll("'","").replaceAll("&"," ");
        var stat = 1;
        var msg = "请求验证计算结果出错！";
        jQuery.ajax({
            type:"post",
            async:false,
            url:"rule?wf_num=R_finance_P039",
            dataType:"text",
            data:{
               valValList:valValList  
            },
            success:function(data){
                var resData = JSON.parse(data);
               stat = resData.stat;
               msg = resData.msg;
            }
        }); 
        return _validateLegal(stat,msg);
    }
}
    
// 计算后验证参数是否合法标识（false：不合法、true：合法）
var _validatePass = true;
function computer0(){
    
    _validatePass = true;
    var rows = $("#dg").datagrid('getRows'); 
    var amount=parseFloat(0.00);
    var tax_amount=parseFloat(0.00);//营改增  可抵扣增值税金额合计
    var Tax_Amount=parseFloat(0.00);//营改增
    var taxSumNo = parseFloat(0.00);//可抵扣非增值税金额合计
    //var added_travelamount_tax = parseFloat(0.00);//交通费可抵扣税额合计
    var sumAir = parseFloat(0.00);//
    var sumCar = parseFloat(0.00);//
    var sumTrain = parseFloat(0.00);//
    var sumEle = parseFloat(0.00);//
    var taxSumAir = parseFloat(0.00);//
    var taxSumCar = parseFloat(0.00);//
    var taxSumTrain = parseFloat(0.00);//
    var taxSumEle = parseFloat(0.00);//
    
    var amountTrval=parseFloat(0.00);
    var VAT=parseFloat(0.00);//营改增VAT
    //最下面的求和
    var Business_traveling=parseFloat(0.00);
    var Staff_communication_expense=parseFloat(0.00);
    var Business_entertainment=parseFloat(0.00);
    var team_building=parseFloat(0.00);
    var Overtime_Meal_Allowance=parseFloat(0.00);
    var employee_benefits=parseFloat(0.00);
    var travel_visa_insurance=parseFloat(0.00);
    var travel_other_transportation=parseFloat(0.00);
    var travel_accommodation=parseFloat(0.00);
    var travel_meals=parseFloat(0.00);
    var travel_communication=parseFloat(0.00);//2017-05-18凭证
    var travel_postage=parseFloat(0.00);//王南修改 20180108
    var travel_office=parseFloat(0.00);
    var travel_air_ticket=parseFloat(0.00);
    var postage=parseFloat(0.00);//凭证
    var postage_VAT=parseFloat(0.00);//凭证
    //营改增VAT
    var Business_traveling_VAT=parseFloat(0.00);
    var Staff_comm_VAT=parseFloat(0.00);
    var Business_enter_VAT=parseFloat(0.00);
    var team_building_VAT=parseFloat(0.00);
    var Overtime_Meal_VAT=parseFloat(0.00);
    var employee_benefits_VAT=parseFloat(0.00);
    var travel_visa_VAT=parseFloat(0.00);
    var travel_other_VAT=parseFloat(0.00);
    var travel_accom_VAT=parseFloat(0.00);
    var travel_meals_VAT=parseFloat(0.00);
    var travel_office_VAT=parseFloat(0.00);
    var travel_air_ticket_VAT=parseFloat(0.00);
    //增加出差天数
    //alert("类型"+$("#doctype").combobox('getValue'));
    if($("#doctype").combobox('getValue')=='fin_travel_foreign'||$("#doctype").combobox('getValue')=='fin_travel_domestic'){
        //alert("进入出差明细金额计算，，，，，，");
        var rowss = $("#dc").datagrid('getRows'); 
        stopEditRow1();
        for(var i=0;i<rowss.length;i++){
            if(rowss[i].travel_days==''||typeof(rowss[i].travel_days)=='undefined'){
                amountTrval+=parseFloat(0.00);
            }else{
    	        amountTrval+=parseFloat(rowss[i].travel_days);
            }
        }
        //alert("合计出差天数======" + amountTrval);
    }
	stopEditRow();
	//计算人民币金额
    for(var i=0;i<rows.length;i++){
        //获取每一行的数据
        FC_Amount=rows[i].FC_Amount;  
        FX_rate=rows[i].FX_rate;
        keyVal=rows[i].Amount;
        tax_Amount=rows[i].tax_amount;//营改增增值税==Y的值得合计
        if_Tax=rows[i].if_tax;//营改增
        Tax_ALLmount=rows[i].tax_amount//营改增的总值
        VAT=rows[i].tax_amount;//营改增VAT
        
        //1）手填： 增值税专用发票、增值税电子普通发票(交通类)、增值税普通发票(其他)
        //2）系统带出：飞机票(可抵扣)、飞机票(不可抵扣)、火车票(实名)、汽车票+船票(实名)、其他发票(非实名)系统自动核算税额。
        //税额结算方式：飞机票(可抵扣)、火车票(实名)=本位币金额/1.09*0.09；汽车票+船票(实名)=本位币金额/1.03*0.03；
        //飞机票(不可抵扣)、其他发票(非实名)=0
        //可抵扣增值税金额: 增值税专用发票、增值税电子普通发票(交通类) 的税额合计
        //可抵扣非增值税金额:增值税普通发票(其他)、飞机票(可抵扣)、火车票(实名)、汽车票+船票(实名) 的税额合计
        //合计数=《增值税专用发票、增值税电子普通发票(交通类)、增值税普通发票(其他)  人民币金额+税额》
        //+《飞机票(可抵扣)、飞机票(不可抵扣)、火车票(实名)、汽车票+船票(实名)、其他发票(非实名) 中人民币金额》
        //交通费可抵扣税额=飞机票(可抵扣) 的税额 + 火车票(实名) 的税额 + 汽车票+船票(实名) 的税额
        //
        
        if(FC_Amount==""||FX_rate==""||keyVal==""){
            amount=parseFloat(0.00);
            //注释
            setEditing(i);
        } 
        if(Tax_ALLmount==""){
            Tax_Amount=parseFloat(0.00);
        }
        // if(tax_Amount == "" || (if_Tax != "增值税专用发票" && if_Tax != "增值税普通发票") ){//营改增当值税专票为N时税额不计入可抵扣增值税金额中N
        //     tax_amount+=parseFloat(0.00);
        //     amount+=parseFloat(rows[i].Amount);
        //     Tax_Amount+=parseFloat(rows[i].tax_amount)//计算税额的求和营改增
        // }else{
        //     amount+=parseFloat(rows[i].Amount);
        //     tax_amount+=parseFloat(rows[i].tax_amount);//营改增
        //     Tax_Amount+=parseFloat(rows[i].tax_amount)//计算税额的求和营改增
        // }
        if(if_Tax == "增值税专用发票" || if_Tax == "增值税电子普通发票(交通类)" || if_Tax == "增值税普通发票"){
           tax_amount += parseFloat(rows[i].tax_amount);
           amount+=parseFloat(rows[i].Amount);
           Tax_Amount+=parseFloat(rows[i].tax_amount);//计算税额的求和营改增
           if(if_Tax == "增值税电子普通发票(交通类)"){
              //var taxSumEle = parseFloat(0.00);//
              taxSumEle += parseFloat(rows[i].tax_amount)
              sumEle += parseFloat(rows[i].Amount) - parseFloat(rows[i].tax_amount);
           }
           
        }else if(if_Tax == "增值税普通发票(其他)" || if_Tax == "飞机票(可抵扣)" || if_Tax == "火车票(实名)" || if_Tax == "汽车票+船票(实名)"){
            if(if_Tax != "增值税普通发票(其他)"){
               taxSumNo += parseFloat(rows[i].tax_amount); 
            }else{
                amount+=parseFloat(rows[i].tax_amount);
            }
	           
            amount+=parseFloat(rows[i].Amount);
            //Tax_Amount+=parseFloat(rows[i].tax_amount)//计算税额的求和营改增
            if(if_Tax == "飞机票(可抵扣)"){
              taxSumAir += parseFloat(rows[i].tax_amount);
              sumAir += parseFloat(rows[i].Amount) - parseFloat(rows[i].tax_amount);
            }else if(if_Tax == "汽车票+船票(实名)"){
              taxSumCar += parseFloat(rows[i].tax_amount)
              sumCar += parseFloat(rows[i].Amount) - parseFloat(rows[i].tax_amount);
            }else if(if_Tax == "火车票(实名)"){
              taxSumTrain += parseFloat(rows[i].tax_amount)
              sumTrain += parseFloat(rows[i].Amount) - parseFloat(rows[i].tax_amount);
            }
           
           
        }else if(if_Tax == "飞机票(不可抵扣)" || if_Tax == "其他发票(非实名)" ){
            amount+=parseFloat(rows[i].Amount);
        }else{
            amount+=parseFloat(rows[i].Amount);
            tax_amount+=parseFloat(rows[i].tax_amount);//营改增
            Tax_Amount+=parseFloat(rows[i].tax_amount);//计算税额的求和营改增
        }
        // if(if_Tax == "飞机票(可抵扣)" || if_Tax == "火车票(实名)" || if_Tax == "汽车票+船票(实名)"){
        //     added_travelamount_tax += parseFloat(rows[i].tax_amount);
        // }
        //最下面求和
        //获取每一行的数据
        keyVal1=rows[i].expenses_item;
        //keyVal2=rows[i].text;
        if(!(keyVal==undefined || keyVal=="" || keyVal==null) && keyVal1=="交通费"){
            if(if_Tax == "增值税专用发票" || if_Tax == "增值税普通发票"){
                Business_traveling+=parseFloat(keyVal);
                Business_traveling_VAT+=parseFloat(rows[i].tax_amount); 
            }else{
                Business_traveling+=(parseFloat(keyVal)+parseFloat(rows[i].tax_amount));
                Business_traveling_VAT+=parseFloat(0.00);      
            }
        }if(!(keyVal==undefined || keyVal=="" || keyVal==null) && keyVal1.indexOf("交通费") != -1){
            Business_traveling+=parseFloat(keyVal);
            Business_traveling_VAT+=parseFloat(rows[i].tax_amount); 
        }else if(!(keyVal==undefined || keyVal=="" || keyVal==null)&&keyVal1=="员工通讯费"){//凭证接口通讯费改员工通讯费
            if(if_Tax == "增值税专用发票" || if_Tax == "增值税普通发票"){
                Staff_communication_expense+=parseFloat(keyVal);
                Staff_comm_VAT+=parseFloat(rows[i].tax_amount); 
            }else{
                Staff_communication_expense+=(parseFloat(keyVal)+parseFloat(rows[i].tax_amount));
                Staff_comm_VAT+=parseFloat(0.00);      
            }
        }else if(!(keyVal==undefined || keyVal=="" || keyVal==null)&&keyVal1=="交际费"){
            if(if_Tax == "增值税专用发票" || if_Tax == "增值税普通发票"){
                Business_entertainment+=parseFloat(keyVal);
                Business_enter_VAT+=parseFloat(rows[i].tax_amount); 
            }else{
                Business_entertainment+=(parseFloat(keyVal)+parseFloat(rows[i].tax_amount));
                Business_enter_VAT+=parseFloat(0.00);      
            }
        }else if(!(keyVal==undefined || keyVal=="" || keyVal==null)&&keyVal1=="团建费"){
            if(if_Tax == "增值税专用发票" || if_Tax == "增值税普通发票"){
                team_building+=parseFloat(keyVal);
                team_building_VAT+=parseFloat(rows[i].tax_amount); 
            }else{
                team_building+=(parseFloat(keyVal)+parseFloat(rows[i].tax_amount));
                team_building_VAT+=parseFloat(0.00);      
            }
        }else if(!(keyVal==undefined || keyVal=="" || keyVal==null)&&keyVal1=="误餐费"){
            if(if_Tax == "增值税专用发票" || if_Tax == "增值税普通发票"){
                Overtime_Meal_Allowance+=parseFloat(keyVal);
                Overtime_Meal_VAT+=parseFloat(rows[i].tax_amount); 
            }else{
                Overtime_Meal_Allowance+=(parseFloat(keyVal)+parseFloat(rows[i].tax_amount));
                Overtime_Meal_VAT+=parseFloat(0.00);      
            }
        }else if(!(keyVal==undefined || keyVal=="" || keyVal==null)&&keyVal1=="职工福利"){
            if(if_Tax == "增值税专用发票" || if_Tax == "增值税普通发票"){
                employee_benefits+=parseFloat(keyVal);
                employee_benefits_VAT+=parseFloat(rows[i].tax_amount); 
            }else{
                employee_benefits+=(parseFloat(keyVal)+parseFloat(rows[i].tax_amount));
                employee_benefits_VAT+=parseFloat(0.00);      
            }
        }else if(!(keyVal==undefined || keyVal=="" || keyVal==null)&&keyVal1=="差旅费-签证和保险"){
            if(if_Tax == "增值税专用发票" || if_Tax == "增值税普通发票"){
                travel_visa_insurance+=parseFloat(keyVal);
                travel_visa_VAT+=parseFloat(rows[i].tax_amount); 
            }else{
                travel_visa_insurance+=(parseFloat(keyVal)+parseFloat(rows[i].tax_amount));
                travel_visa_VAT+=parseFloat(0.00);      
            }
        }else if(!(keyVal==undefined || keyVal=="" || keyVal==null)&&keyVal1=="差旅费-其他交通费"){
            if(if_Tax == "增值税专用发票" || if_Tax == "增值税普通发票"){
                travel_other_transportation+=parseFloat(keyVal);
                travel_other_VAT+=parseFloat(rows[i].tax_amount); 
            }else{
                travel_other_transportation+=(parseFloat(keyVal)+parseFloat(rows[i].tax_amount));
                travel_other_VAT+=parseFloat(0.00);      
            }
        }else if(!(keyVal==undefined || keyVal=="" || keyVal==null) && keyVal1.indexOf("差旅费-其他交通") != -1){
            if(if_Tax == "增值税普通发票(其他)"){
                travel_other_transportation+=parseFloat(keyVal);
                travel_other_VAT+=parseFloat(rows[i].tax_amount); 
            }else{
                travel_other_transportation+=(parseFloat(keyVal)+parseFloat(rows[i].tax_amount));
                travel_other_VAT+=parseFloat(0.00);      
            }
        }else if(!(keyVal==undefined || keyVal=="" || keyVal==null)&&keyVal1=="差旅费-住宿费"){
            if(if_Tax == "增值税专用发票" || if_Tax == "增值税普通发票"){
                travel_accommodation+=parseFloat(keyVal);
                travel_accom_VAT+=parseFloat(rows[i].tax_amount); 
            }else{
                travel_accommodation+=(parseFloat(keyVal)+parseFloat(rows[i].tax_amount));
                travel_accom_VAT+=parseFloat(0.00);      
            }
        }else if(!(keyVal==undefined || keyVal=="" || keyVal==null)&&keyVal1=="差旅费-餐费"){
            if(if_Tax == "增值税专用发票" || if_Tax == "增值税普通发票"){
                travel_meals+=parseFloat(keyVal);
                travel_meals_VAT+=parseFloat(rows[i].tax_amount); 
            }else{
                travel_meals+=(parseFloat(keyVal)+parseFloat(rows[i].tax_amount));
                travel_meals_VAT+=parseFloat(0.00);      
            }
        }else if(!(keyVal==undefined || keyVal=="" || keyVal==null)&&keyVal1=="差旅费-办公费"){
            if(if_Tax == "增值税专用发票" || if_Tax == "增值税普通发票"){
                travel_office+=parseFloat(keyVal);
                travel_office_VAT+=parseFloat(rows[i].tax_amount); 
            }else{
                travel_office+=(parseFloat(keyVal)+parseFloat(rows[i].tax_amount));
                travel_office_VAT+=parseFloat(0.00);      
            }
        }else if(!(keyVal==undefined || keyVal=="" || keyVal==null)&&keyVal1=="差旅费-机票"){
            if(if_Tax == "增值税专用发票" || if_Tax == "增值税普通发票"){
                travel_air_ticket+=parseFloat(keyVal);
                travel_air_ticket_VAT+=parseFloat(rows[i].tax_amount); 
            }else{
                travel_air_ticket+=(parseFloat(keyVal)+parseFloat(rows[i].tax_amount));
                travel_air_ticket_VAT+=parseFloat(0.00);      
            }
        }else if(!(keyVal==undefined || keyVal=="" || keyVal==null) && keyVal1=="差旅费-机票(可抵扣)"){
            travel_air_ticket+=parseFloat(keyVal);
            travel_air_ticket_VAT+=parseFloat(rows[i].tax_amount); 
        }else if(!(keyVal==undefined || keyVal=="" || keyVal==null)&&keyVal1=="差旅费-员工通讯费"){
            if(if_Tax == "增值税专用发票" || if_Tax == "增值税普通发票"){
                travel_communication+=parseFloat(keyVal);
                //   travel_air_ticket_VAT+=parseFloat(rows[i].tax_amount); 
            }else{
                travel_communication+=(parseFloat(keyVal)+parseFloat(rows[i].tax_amount));
                //  travel_air_ticket_VAT+=parseFloat(0.00);      
            }
        }else if(!(keyVal==undefined || keyVal=="" || keyVal==null)&&keyVal1=="差旅费-邮寄费"){
            if(if_Tax == "增值税专用发票" || if_Tax == "增值税普通发票"){
                travel_postage += parseFloat(keyVal);
            }else{
                travel_postage += (parseFloat(keyVal) + parseFloat(rows[i].tax_amount));
            }
        }else if(!(keyVal==undefined || keyVal=="" || keyVal==null)&&keyVal1=="邮寄费"){
            if(if_Tax == "增值税专用发票" || if_Tax == "增值税普通发票"){
                postage+=parseFloat(keyVal);
                postage_VAT+=parseFloat(rows[i].tax_amount); 
            }else{
                postage+=(parseFloat(keyVal)+parseFloat(rows[i].tax_amount));
                postage_VAT+=parseFloat(0.00);      
            }
        }else{
          
        }
    }

    //2017-05-18凭证将请求放到合计之前
	jQuery.ajax({
        type:"post",
        async:false,
        url:"rule?wf_num=R_finance_B016",
        dataType:"text",
        data:{
            DocUnid:$("#WF_DocUnid").val(),
          // travel_days:$("#travel_days").val(),
            staff_id:$("#staff_id").val(),
            travel_days:amountTrval,
            doctype:$("#doctype").combobox('getValue')
        },
        success:function(data) {//2017-05-18凭证
        var d = eval("("+data+")");//2017-05-18凭证
        var tet=parseFloat(d.meal)+parseFloat(d.phone)+parseFloat(amount)+parseFloat(Tax_Amount);//营改增//2017-05-18凭证
        travel_meals+=parseFloat(d.meal);//2017-05-18凭证
        travel_communication+=parseFloat(d.phone);//2017-05-18凭证
        $("#text9").val(tet.toFixed(2));
        $("#text10").val(DX(tet.toFixed(2)));
      
        }
    });
    //新增应付合计text13
    var x= $("#text9").val();
    var littleAmount=x- $("#text12").val();
    var littleAmount1=$("#text12").val()-x;
    if(littleAmount<0){
        $("#text13").val('0'); 
        $("#text17").val('零');
        //应退回公司text14
        $("#text14").val(littleAmount1); 
        $("#text18").val(DX(littleAmount1)); 
    }else{
        $("#text13").val(littleAmount);
        $("#text17").val(DX( $("#text13").val()));
        $("#text14").val('0'); 
        $("#text18").val('零'); 
    } 
    var xx=$("#text12").val();
    if($("#text12").val()=='0'){
        $("#text16").val('零');  
    }else{
        $("#text16").val(DX( $("#text12").val()));
    }
	$("#text11").val(amount.toFixed(2));
	$("#text15").val(DX(amount.toFixed(2)));
	//营改增
   	//$("#added_amount_tax").val(tax_amount.toFixed(2));
   	$("#added_amount_tax").val(tax_amount.toFixed(2));//可抵扣增值税金额
   	$("#added_noamount_tax").val(taxSumNo.toFixed(2));//可抵扣非增值税金额
   	//$("#added_travelamount_tax").val(added_travelamount_tax.toFixed(2));//交通费税额
   	$("#added_airamount").val(sumAir.toFixed(2));//
   	$("#added_caramount").val(sumCar.toFixed(2));//
   	$("#added_trainamount").val(sumTrain.toFixed(2));//
   	$("#added_eleamount").val(sumEle.toFixed(2));//
   	
   	$("#added_airamount_tax").val(taxSumAir.toFixed(2));//
   	$("#added_caramount_tax").val(taxSumCar.toFixed(2));//
   	$("#added_trainamount_tax").val(taxSumTrain.toFixed(2));//
   	$("#added_eleamount_tax").val(taxSumEle.toFixed(2));//

	//最下面求和
	$("#Business_traveling").val(Business_traveling.toFixed(2));
    $("#Staff_communication_expense").val(Staff_communication_expense.toFixed(2));
    $("#Business_entertainment").val(Business_entertainment.toFixed(2));
    $("#team_building").val(team_building.toFixed(2));
    $("#Overtime_Meal_Allowance").val(Overtime_Meal_Allowance.toFixed(2));
    $("#employee_benefits").val(employee_benefits.toFixed(2));
    $("#travel_visa_insurance").val(travel_visa_insurance.toFixed(2));
    $("#travel_other_transportation").val(travel_other_transportation.toFixed(2));
    $("#travel_accommodation").val(travel_accommodation.toFixed(2));
    $("#travel_meals").val(travel_meals.toFixed(2));
    $("#travel_communication").val(travel_communication.toFixed(2));//2017-05-18凭证
    $("#travel_postage").val(travel_postage.toFixed(2));//王南修改 20180108
    $("#postage").val(postage.toFixed(2));//2017-05-18凭证
    $("#postage_VAT").val(postage_VAT.toFixed(2));//凭证
    $("#travel_office").val(travel_office.toFixed(2));
    $("#travel_air_ticket").val(travel_air_ticket.toFixed(2));
    //营改增VAT求和
    
    $("#Business_traveling_VAT").val(Business_traveling_VAT.toFixed(2));//
    $("#Staff_comm_VAT").val(Staff_comm_VAT.toFixed(2));//Business_traveling_VAT
    $("#Business_enter_VAT").val(Business_enter_VAT.toFixed(2));
    $("#team_building_VAT").val(team_building_VAT.toFixed(2));
    $("#Overtime_Meal_VAT").val(Overtime_Meal_VAT.toFixed(2));
    $("#employee_benefits_VAT").val(employee_benefits_VAT.toFixed(2));
    $("#travel_visa_VAT").val(travel_visa_VAT.toFixed(2));
    $("#travel_other_VAT").val(travel_other_VAT.toFixed(2));
    $("#travel_accom_VAT").val(travel_accom_VAT.toFixed(2));
    $("#travel_meals_VAT").val(travel_meals_VAT.toFixed(2));
    
    $("#travel_office_VAT").val(travel_office_VAT.toFixed(2));
    $("#travel_office").val(travel_office.toFixed(2));
    $("#travel_air_ticket_VAT").val(travel_air_ticket_VAT.toFixed(2));

    //营改增VAT
    document.getElementById("Staff_comm_VAT").readOnly="readonly";
    document.getElementById("Business_traveling_VAT").readOnly="readonly";
    document.getElementById("Business_enter_VAT").readOnly="readonly";   
    document.getElementById("team_building_VAT").readOnly="readonly";
    document.getElementById("Overtime_Meal_VAT").readOnly="readonly";
    
    document.getElementById("employee_benefits_VAT").readOnly="readonly";
    document.getElementById("travel_visa_VAT").readOnly="readonly";
    document.getElementById("travel_other_VAT").readOnly="readonly";   
    document.getElementById("travel_accom_VAT").readOnly="readonly";
    document.getElementById("travel_meals_VAT").readOnly="readonly";   
    document.getElementById("travel_office_VAT").readOnly="readonly";
    document.getElementById("travel_air_ticket_VAT").readOnly="readonly";   
    document.getElementById("postage_VAT").readOnly="readonly"; //凭证
    document.getElementById("postage").readOnly="readonly"; //凭证
    //结束
    document.getElementById("text9").readOnly="readonly";
    document.getElementById("text10").readOnly="readonly";
    document.getElementById("added_amount_tax").readOnly="readonly";//营改增
    
    document.getElementById("added_noamount_tax").readOnly="readonly";//营改增
    document.getElementById("added_airamount_tax").readOnly="readonly";//营改增
    document.getElementById("added_caramount_tax").readOnly="readonly";//营改增
    document.getElementById("added_trainamount_tax").readOnly="readonly";//营改增
    document.getElementById("added_eleamount_tax").readOnly="readonly";//营改增
    
    document.getElementById("text13").readOnly="readonly";
    document.getElementById("text14").readOnly="readonly";   
    document.getElementById("text17").readOnly="readonly";
    document.getElementById("text18").readOnly="readonly";   
   
    document.getElementById("Business_traveling").readOnly="readonly";   
    document.getElementById("Staff_communication_expense").readOnly="readonly";
    document.getElementById("Business_entertainment").readOnly="readonly";  
    document.getElementById("team_building").readOnly="readonly";   
    document.getElementById("Overtime_Meal_Allowance").readOnly="readonly";
    document.getElementById("employee_benefits").readOnly="readonly";   
    
    document.getElementById("travel_visa_insurance").readOnly="readonly";   
    document.getElementById("travel_other_transportation").readOnly="readonly";
    document.getElementById("travel_accommodation").readOnly="readonly";   
    document.getElementById("travel_meals").readOnly="readonly"; 
    document.getElementById("travel_communication").readOnly="readonly";   //2017-05-18
    document.getElementById("travel_postage").readOnly="readonly";   //王南修改 20180108
    document.getElementById("travel_office").readOnly="readonly";
    document.getElementById("travel_air_ticket").readOnly="readonly"; 
    var vParams= _validateParams();
        if(vParams.stat==1){// js验证计算不通过
          // js验证数据出错
          alert(vParams.msg); 
          _validatePass = false;
        }else{
            vParams = validateParams();
            if(vParams.stat==1){// js验证计算通过，进行后台验证计算
                // 后台验证数据出错
                alert(vParams.msg); 
                _validatePass = false;
            }
        }
}
//数字转大写
 function DX(n) {
        if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n))
            return "数据非法";
        var unit = "千百拾亿千百拾万千百拾元角分", str = "";
            n += "00";
        var p = n.indexOf('.');
        if (p >= 0)
            n = n.substring(0, p) + n.substr(p+1, 2);
            unit = unit.substr(unit.length - n.length);
        for (var i=0; i < n.length; i++)
            str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i);
        return str.replace(/零(千|百|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "$1").replace(/(亿)万|壹(拾)/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "元整");
}
function SaveDocumentCallBack(btnAction,rs){
	//保存成功后的回调函数
  	//凭证接口
  	//alert("保存成功后的回调函数");
  	//var WF_CurrentNodeid=$('#WF_CurrentNodeid').val();
  	var WF_DocUnid = $("#WF_DocUnid").val();
    var createTime = "";
    if($('#WF_CurrentNodeid').val()=='T10002'){
        //手工结束该日常费用报销单关联的出差计划单流程
        //var TravelNo = $("#TravelNo").val();
        var TravelNo = $("#TravelNo").combobox('getValue');
        jQuery.ajax({
            type: "post",
            async: true,          
            url: "rule?wf_num=R_finance_B062",
            dataType: "text",
            data:{
                TravelNo: TravelNo
            },
            success: function (data) {
                //createTime = data;
                //alert("手工结束该日常费用报销单关联的出差计划单流程");
            }
        });
        
    }
    
    jQuery.ajax({
        type: "post",
        async: false,          
        url: "rule?wf_num=R_finance_B049",
        dataType: "text",
        data:{
            WF_DocUnid: WF_DocUnid
        },
        success: function (data) {
            //createTime = data.msg;
            createTime = data;
            //alert("createTime=====" + createTime);
        }
    });
    //alert("该单据的申请日期是：" + createTime);
    if($('#WF_CurrentNodeid').val()=='T10024'){
        var comCode = $('#comCode').combobox('getValue');
        //UFDATA_021_2015 北京咨询  UFDATA_032_2014  杭州检验所  UFDATA_042_2017 广州欧蒙医学检验所有限公司
        if(comCode == "UFDATA_021_2015" || comCode == "UFDATA_032_2014" || comCode == "UFDATA_042_2017"){
            alert("该账套已迁移至检验所，请手工生成凭证！");
        }else{
            if(createTime < '2017-12-01'){
          	    alert("此报销单申请时间早于2017年12月1日，请手工生成凭证！");
          	}else{
          	   //使用10.0.13.26服务器上的nginx进行反向代理，因为有SSL证书，不会出现警告提示 王南添加 20180315
          	   //https://api.oumeng.com.cn/PZAPI/AddPZVouch.aspx
          	   //var url="https://192.168.13.193:8443/PZAPI/AddPZVouch.aspx?content={cCode:'"+WF_DocUnid+"',cType:'GL',cVouchType:'日常报销'}";
               //addScriptTag(encodeURI("https://192.168.13.193:8443/PZAPI/AddPZVouch.aspx?content={cCode:'"+WF_DocUnid+"',cType:'GL',cVouchType:'日常报销'}&callback=successCallback")); 
               
               // api.oumeng.com.cn 
            //   var url="https://api.oumeng.com.cn/PZAPI/AddPZVouch.aspx?content={cCode:'"+WF_DocUnid+"',cType:'GL',cVouchType:'日常报销'}";
               addScriptTag(encodeURI("https://api.oumeng.com.cn/PZAPI/AddPZVouch.aspx?content={cCode:'"+WF_DocUnid+"',cType:'GL',cVouchType:'日常报销'}&callback=successCallback")); 
          	}
            // alert(rs.msg); //提交成功后增加提醒
            // location.href="view?wf_num=V_S005_G001";
            // try{
            //     opener.$('#dg').datagrid('reload');
            // }catch(e){}
            // window.close(); 
        }
        
    }else{ 
        alert(rs.msg); //提交成功后增加提醒
        location.href="view?wf_num=V_S005_G001";
        try{
            opener.$('#dg').datagrid('reload');
        }catch(e){}
        window.close(); 
    }
}
//凭证接口
function addScriptTag(src) {
  var script = document.createElement('script');
  script.setAttribute("type","text/javascript");
  script.src = src;
  //alert("凭证接口页面script====" + script);
  document.body.appendChild(script);
}
//凭证接口
function successCallback(data) {
    
    //alert("凭证接口回调函数：" + data.result+data.failReason);
    if (data.result=="true"){
          result="成功"; 
              
    }else if(data.result=="false"){
          result="失败"; 
    }
    failReason=data.failReason;
    alert("凭证生成状态："+result+"\n流程id："+failReason);
    console.log('response data: ' + JSON.stringify(data));
    window.close();
};		
function getNewMsg(msg){
    var url = "rule?wf_num=R_MDM_P033&msg="+encodeURIComponent(msg);
    var rs = "";
    jQuery.ajax({
        type: "post",
        async: false,          
        url: url,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {
            rs = data.msg;
        }
    });
    return rs;
}
//根据公司查询预算部门()
function initfirstCombox(rowIndex){
    var comCode=$('#comCode').combobox('getValue');
    //var userid=$("#WF_UserName").val();
    var userid=$("#staff_id").val();//凭证
    var doctype = $('#doctype').combobox('getValue');//选择报销类型
    var row = $('#dg').datagrid('getSelected',rowIndex);
    //	var row = $("#dg").datagrid('getRows');
	var target = $('#dg').datagrid('getEditor', {index:rowIndex,'field':'budget_dept'}).target;
	var rows = $("#dg").datagrid('getRows');
    var str = rows[rowIndex]['budget_dept'];
    var tax = rows[rowIndex]['if_tax'];
    var url = 'rule?wf_num=R_finance_B006&userid='+userid+'&comCode='+comCode;
    //target.combobox('reload', url).combobox({"editable":false});//联动下拉列表重载插件id
    target.combobox({ 
    	url:url,
    	valueField:'id',
    	textField:'text',
    	onLoadSuccess : function() {
	        var  groupdata1 = target.combobox('getData');
	        if(groupdata1.length > 0){
	           for (var i = 0; i < groupdata1.length; i++) { 
                    if (groupdata1[i].id == str) {  
                        target.combobox('select', str);  //循环判断，如果某项一致，则该项选中  
                    }  
                }  
	        }else{
	            target.combobox('select', str);  //
	        }
    	},
    	onSelect:function(rec) {
            /////////////////////////////
            //var budgetDept = target.combobox('getValue');
            var if_taxTarget = $('#dg').datagrid('getEditor', {index:rowIndex,'field':'if_tax'}).target;
        	var if_tax = if_taxTarget.combobox('getValue');//发票类型
        	//alert("if_tax$$$$===" + if_tax);
            
            var expense = rows[rowIndex]['expenses_item'];
            var expenseTarget = $('#dg').datagrid('getEditor', {index:rowIndex,'field':'expenses_item'}).target;
            var expenseUrl = 'rule?wf_num=R_finance_B007&userid='+userid+'&comCode='+comCode+'&doctype='+doctype+'&if_tax='+if_tax;
            expenseTarget.combobox({ 
                url:expenseUrl,
            	valueField:'id',
            	textField:'text',
            	onLoadSuccess : function() {
        	        var  expenseValue = expenseTarget.combobox('getData');
        	        //alert("expenseValue====" + expenseValue);
        	        if(expenseValue.length > 0){
        	           for (var i = 0; i < expenseValue.length; i++) { 
                            if (expenseValue[i].id == expense) {
                                expenseTarget.combobox('select', expense); //循环判断，如果某项一致，则该项选中  
                            }  
                        }  
        	        }else{
        	            expenseTarget.combobox('select', expense);  //
        	        }
            	},
            	onSelect:function(rec) {
            	    var expensesItem = expenseTarget.combobox('getValue');
            	    var budgetItemTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'budget_item'}).target;
                    var budgetItemUrl = 'rule?wf_num=R_finance_B008&expense='+encodeURIComponent(expensesItem)+'&comCode='+comCode+'&userid='+userid;
                    budgetItemTarget.combobox({ 
                    	url:budgetItemUrl,
                    	valueField:'id',
                    	textField:'text',
                    	onLoadSuccess : function() {
                    	       var  budgetItemGroupdata1 = budgetItemTarget.combobox('getData');
                               if (budgetItemGroupdata1 && budgetItemGroupdata1.length==1) {
                	                 budgetItemTarget.combobox("select",budgetItemGroupdata1[0].text);
                	                 budgetItemTarget.combobox('disable');
                		      }
                    	}
                    }).combobox({"editable":false});
            	    /////////////////////
            	}
            }).combobox({"editable":false});
            ////////////////////////////
        }
    }).combobox({"editable":false});
    
    //////////////////////////////
    //选择发票类型
    
    var taxTarget = $('#dg').datagrid('getEditor', {index:rowIndex,'field':'if_tax'}).target;
    var taxUrl = 'rule?wf_num=R_finance_B048&doctype=' + doctype;
    taxTarget.combobox({ 
        url:taxUrl,
    	valueField:'id',
    	textField:'text',
    	onLoadSuccess : function() {
	        var  taxValue = taxTarget.combobox('getData');
	        if(taxValue.length > 0){
	           for (var i = 0; i < taxValue.length; i++) { 
                    if (taxValue[i].id == tax) {
                        taxTarget.combobox('select', tax); //循环判断，如果某项一致，则该项选中  
                    }  
                }  
	        }else{
	            taxTarget.combobox('select', tax);  //
	        }
    	},
    	onSelect:function(rec) {
    	    var taxTargetValue = taxTarget.combobox('getValue');
    	    var taxAmountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'tax_amount'}).target;
    	    var amountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'Amount'}).target;
    	    var amount = parseFloat(amountTarget.val());
    	    var noTaxAmountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'noTaxAmount'}).target;
    	    //1）手填： 增值税专用发票、增值税电子普通发票(交通类)、增值税普通发票(其他)
            //2）系统带出：飞机票(可抵扣)、飞机票(不可抵扣)、火车票(实名)、汽车票+船票(实名)、其他发票(非实名)系统自动核算税额。
            //税额结算方式：飞机票(可抵扣)、火车票(实名)=本位币金额/1.09*0.09；汽车票+船票(实名)=本位币金额/1.03*0.03；
            //增值税普通发票(其他)、飞机票(不可抵扣)、其他发票(非实名)=0
    	    if(taxTargetValue == "增值税专用发票" || taxTargetValue == "增值税电子普通发票(交通类)" || taxTargetValue == "增值税普通发票(其他)"){
    	       // if(taxAmountTarget.val() != "0" || taxAmountTarget.val() != "0.00"){}else{taxAmountTarget.val(0.00);}
    	        if(taxAmountTarget.val() != "0" || taxAmountTarget.val() != "0.00"){
    	           // taxAmountTarget.val(0.00);
    	            $('#dg').datagrid('getEditor', { index: rowIndex, field: 'tax_amount'}).target.numberbox("setValue",0.00);
    	        }
    	        $(taxAmountTarget).attr("disabled", false);
    	        taxAmountTarget.prop('style','background-color: rgb(255, 255, 255);');
    	        noTaxAmountTarget.val(amount);
    	        $(noTaxAmountTarget).attr("disabled", true);
    	        noTaxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
    	    }else if(taxTargetValue == "飞机票(可抵扣)" || taxTargetValue == "火车票(实名)"){
    	        //alert("amountTarget.val()====" + amountTarget.val());
    	        var taxAmountValue = (amount / 1.09 * 0.09).toFixed(2);
    	        var taxAmount = taxAmountValue;
    	        taxAmountTarget.val(taxAmount);
    	        $(taxAmountTarget).attr("disabled", true);
    	        taxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
    	        noTaxAmountTarget.val(amount - taxAmountValue);
    	        $(noTaxAmountTarget).attr("disabled", true);
    	        noTaxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
    	    }else if(taxTargetValue == "汽车票+船票(实名)"){
    	        //alert("amountTarget.val()****" + amountTarget.val());
    	        var taxAmountValue = (amount / 1.03 * 0.03).toFixed(2);
    	        var taxAmount = taxAmountValue;
    	        taxAmountTarget.val(taxAmount);
    	        $(taxAmountTarget).attr("disabled", true);
    	        taxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
    	        noTaxAmountTarget.val(amount - taxAmountValue);
    	        $(noTaxAmountTarget).attr("disabled", true);
    	        noTaxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
    	    }else{
    	       // if(taxAmountTarget.val() != "0" || taxAmountTarget.val() != "0.00"){}else{taxAmountTarget.val(0.00);}
    	       if(taxAmountTarget.val() != "0" || taxAmountTarget.val() != "0.00"){
    	           taxAmountTarget.val(0.00);
    	           
    	       }
    	       noTaxAmountTarget.val(amount);
    	       if(taxTargetValue != "增值税电子普通发票(非交通类)"){
    	            $(taxAmountTarget).attr("disabled", true);
                    taxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
                    
                    $(noTaxAmountTarget).attr("disabled", true);
                    noTaxAmountTarget.prop('style','background-color: rgb(204, 204, 204);'); 
    	       }
    	        
    	    }
    	    
    	    /////////////////////////////
            //var budgetDept = target.combobox('getValue');
            var expense = rows[rowIndex]['expenses_item'];
            var expenseTarget = $('#dg').datagrid('getEditor', {index:rowIndex,'field':'expenses_item'}).target;
            var expenseUrl = 'rule?wf_num=R_finance_B007&userid='+userid+'&comCode='+comCode+'&doctype='+doctype+'&if_tax='+taxTargetValue;
            expenseTarget.combobox({ 
                url:expenseUrl,
            	valueField:'id',
            	textField:'text',
            	onLoadSuccess : function() {
        	        var  expenseValue = expenseTarget.combobox('getData');
        	        //alert("expenseValue====" + expenseValue);
        	        if(expenseValue.length > 0){
        	           for (var i = 0; i < expenseValue.length; i++) { 
                            if (expenseValue[i].id == expense) {
                                expenseTarget.combobox('select', expense); //循环判断，如果某项一致，则该项选中  
                            }  
                        }  
        	        }else{
        	            expenseTarget.combobox('select', expense);  //
        	        }
            	},
            	onSelect:function(rec) {
            	    var expensesItem = expenseTarget.combobox('getValue');
            	    var budgetItemTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'budget_item'}).target;
                    var budgetItemUrl = 'rule?wf_num=R_finance_B008&expense='+encodeURIComponent(expensesItem)+'&comCode='+comCode+'&userid='+userid;
                    budgetItemTarget.combobox({ 
                    	url:budgetItemUrl,
                    	valueField:'id',
                    	textField:'text',
                    	onLoadSuccess : function() {
                    	       var  budgetItemGroupdata1 = budgetItemTarget.combobox('getData');
                               if (budgetItemGroupdata1 && budgetItemGroupdata1.length==1) {
                	                 budgetItemTarget.combobox("select",budgetItemGroupdata1[0].text);
                	                 budgetItemTarget.combobox('disable');
                		      }
                    	}
                    }).combobox({"editable":false});
            	    /////////////////////
            	}
            }).combobox({"editable":false});
            ////////////////////////////
    	    
    	}
    }).combobox({"editable":false});
    ///////////////////////
    //numberbox事件触发
    //填写本位币金额
    var amountTarget = $('#dg').datagrid('getEditor', { index: rowIndex, field: 'Amount'}).target;
    amountTarget.numberbox({ 
    	onChange:function(newValue,oldValue) {
    	    var taxTargetValue = taxTarget.combobox('getValue');
    	    var taxAmountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'tax_amount'}).target;
    	    var noTaxAmountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'noTaxAmount'}).target;
    	    //1）手填： 增值税专用发票、增值税电子普通发票(交通类)、增值税普通发票(其他)
            //2）系统带出：飞机票(可抵扣)、飞机票(不可抵扣)、火车票(实名)、汽车票+船票(实名)、其他发票(非实名)系统自动核算税额。
            //税额结算方式：飞机票(可抵扣)、火车票(实名)=本位币金额/1.09*0.09；汽车票+船票(实名)=本位币金额/1.03*0.03；
            //增值税普通发票(其他)、飞机票(不可抵扣)、其他发票(非实名)=0
    	    if(taxTargetValue == "增值税专用发票" || taxTargetValue == "增值税电子普通发票(交通类)" || taxTargetValue == "增值税普通发票(其他)"){
    	        if(taxAmountTarget.val() != "0" || taxAmountTarget.val() != "0.00"){}else{taxAmountTarget.val(0.00);}
    	        $(taxAmountTarget).attr("disabled", false);
    	        taxAmountTarget.prop('style','background-color: rgb(255, 255, 255);');
    	        noTaxAmountTarget.val(parseFloat(newValue));
    	        $(noTaxAmountTarget).attr("disabled", true);
    	        noTaxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
    	    }else if(taxTargetValue == "飞机票(可抵扣)" || taxTargetValue == "火车票(实名)"){
                var taxAmountValue = (parseFloat(newValue) / 1.09 * 0.09).toFixed(2);
    	        var taxAmount = taxAmountValue;
    	        taxAmountTarget.val(taxAmount);
    	        $(taxAmountTarget).attr("disabled", true);
    	        taxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
    	        noTaxAmountTarget.val(parseFloat(newValue) - taxAmountValue);
    	        $(noTaxAmountTarget).attr("disabled", true);
    	        noTaxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
    	    }else if(taxTargetValue == "汽车票+船票(实名)"){
                var taxAmountValue = (parseFloat(newValue) / 1.03 * 0.03).toFixed(2);
    	        var taxAmount = taxAmountValue;
    	        taxAmountTarget.val(taxAmount);
    	        $(taxAmountTarget).attr("disabled", true);
    	        taxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
    	        noTaxAmountTarget.val(parseFloat(newValue) - taxAmountValue);
    	        $(noTaxAmountTarget).attr("disabled", true);
    	        noTaxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
    	    }else{
    	        if(taxAmountTarget.val() != "0" || taxAmountTarget.val() != "0.00"){}else{taxAmountTarget.val(0.00);}
    	        noTaxAmountTarget.val(parseFloat(newValue));
    	        if(taxTargetValue != "增值税电子普通发票(非交通类)"){
        	        $(taxAmountTarget).attr("disabled", true);
        	        taxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
        	        
        	        $(noTaxAmountTarget).attr("disabled", true);
        	        noTaxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
    	        }
    	    }
    	    
    	    
    	}
    });
    //////////////////////
    //numberbox事件触发
    //填写税额
    var taxAmountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'tax_amount'}).target;
    
    taxAmountTarget.numberbox({ 
    	onChange:function(newValue,oldValue) {

    	    var taxTargetValue = taxTarget.combobox('getValue');
    	    var amountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'Amount'}).target;
    	    var amount = parseFloat(amountTarget.val());
    	    
    	    var noTaxAmountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'noTaxAmount'}).target;
    	    //1）手填： 增值税专用发票、增值税电子普通发票(交通类)、增值税普通发票(其他)
            //2）系统带出：飞机票(可抵扣)、飞机票(不可抵扣)、火车票(实名)、汽车票+船票(实名)、其他发票(非实名)系统自动核算税额。
            //税额结算方式：飞机票(可抵扣)、火车票(实名)=本位币金额/1.09*0.09；汽车票+船票(实名)=本位币金额/1.03*0.03；
            //增值税普通发票(其他)、飞机票(不可抵扣)、其他发票(非实名)=0
    	    if(taxTargetValue == "增值税专用发票" || taxTargetValue == "增值税电子普通发票(交通类)" || taxTargetValue == "增值税普通发票(其他)"){
    	        taxAmountTarget.val(parseFloat(newValue));
    	        noTaxAmountTarget.val(amount - parseFloat(newValue));
    	        $(noTaxAmountTarget).attr("disabled", true);
    	        noTaxAmountTarget.prop('style','background-color: rgb(204, 204, 204);');
    	    }
    	}
    });
    taxAmountTarget.numberbox({ 
    	onSelect:function(res) {
    	    
    	   var taxAmountTarget = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'tax_amount'}).target; 
    	}
    });
    /////////////////////////////
    

}
//expenses_item 费用类别
function secondCombox(rowIndex){
//     var comCode=$('#comCode').combobox('getValue');
//     var doctype=$('#doctype').combobox('getValue');
//     // var userid=$("#WF_UserName").val();
//       var userid=$("#staff_id").val();//凭证
//     var row = $('#dg').datagrid('getSelected',rowIndex);
// 	var target = $('#dg').datagrid('getEditor', {index:rowIndex,'field':'expenses_item'}).target;
// 	var rows = $("#dg").datagrid('getRows');
//     var str = rows[rowIndex]['expenses_item'];
//     //alert("str====" + str);
//     var url = 'rule?wf_num=R_finance_B007&userid='+userid+'&comCode='+comCode+'&doctype='+doctype;
//     //target.combobox('reload', url).combobox({"editable":false});//联动下拉列表重载插件id
//     target.combobox({ 
//     	url:url,
//     	valueField:'id',
//     	textField:'text',
//     	onLoadSuccess : function() {
//     	        var  groupdata1 = target.combobox('getData');
//     	        if(groupdata1.length > 0){
//     	           for (var i = 0; i < groupdata1.length; i++) { 
//                         if (groupdata1[i].id == str) {  
//                             target.combobox('select', str);  //循环判断，如果某项一致，则该项选中  
//                         }  
//                     }  
//     	        }else{
//     	            target.combobox('select', str);  //
//     	        }
                
//     	}
//     }).combobox({"editable":false});
    
}
//二级联动  预算项目
function initSecondCombox(data){
    // var comCode=$('#comCode').combobox('getValue');
    // // var userid=$("#WF_UserName").val();
    // var userid=$("#staff_id").val();//凭证
    // var row = $('#dg').datagrid('getSelected');
    // var rowIndex = $('#dg').datagrid('getRowIndex',row);//获取行号
    // var targets = $('#dg').datagrid('getEditor', {'index':rowIndex,'field':'budget_item'}).target;
    // var url = 'rule?wf_num=R_finance_B008&expense='+encodeURIComponent(data)+'&comCode='+comCode+'&userid='+userid;
    // targets.combobox({ 
    // 	url:url,
    // 	valueField:'id',
    // 	textField:'text',
    // 	onLoadSuccess : function() {
    // 	       var  groupdata1 = targets.combobox('getData');
    //           if (groupdata1 && groupdata1.length==1) {
	   //              targets.combobox("select",groupdata1[0].text);
	   //              targets.combobox('disable');
		  //    }
    // 	}
    // }).combobox({"editable":false});
}
 var editFlag = undefined;//设置一个编辑标记，原来的位置

 $(document).ready(function(){
      var comCodeTag = $("#comCode")[0].tagName.toLocaleLowerCase();
      //span标签为只读状态，不加载事件
    if(comCodeTag!="span"){
      //获得登陆用户id
    //   var userid=$("#WF_UserName").val();
   var userid=$("#staff_id").val();//凭证
    $("#comCode").combobox({   
         url:"rule?wf_num=R_finance_B005&userid="+userid,
        valueField:'val', 
        textField:'text',
        	onLoadSuccess:function() {
    		    groupdata = $('#comCode').combobox('getData');
    		    if (groupdata && groupdata.length==1) {
    		        $('#comCode').combobox("select",groupdata[0].val);
    		    } 
    		},
    			onSelect:function(rec) {
    		    $('#cost_center').combobox({
    		          url:"rule?wf_num=R_finance_B004&userid="+userid+"&comCode="+$('#comCode').combobox('getValue'),
    		          valueField:'val',
    		          textField:'text',
    		          onLoadSuccess:function() {
    		              groupdata1 = $('#cost_center').combobox('getData');
    		              if (groupdata1 && groupdata1.length==1) {
    		                  $('#cost_center').combobox("select",groupdata1[0].val);
    		              }
    		          }
    	         });
    		}
    });
   
     var WF_DocUnid=$("#WF_DocUnid").val(); 
     //判断是否为驳回单据
     var res = 1;
    $.ajax({
    url:'r?wf_num=R_finance_B025&WF_DocUnid='+WF_DocUnid,
    dataType:'json',
    cache:false,
    async:false, 
    success:function(data) {
        res = data;
    }
});
//驳回状态
if(res>0){
   // alert("进入驳回状态");
        $('#bank_A_C').combobox({
            url:"rule?wf_num=R_finance_B024&userid="+userid+"&WF_DocUnid="+WF_DocUnid,
            valueField:'val',
            textField:'text'
     });
}
if(res<0 && $("#WF_DocStatus").val()!='Draft'){
  //  alert("进入非驳回状态");
      $('#bank_A_C').combobox({
                  url:"rule?wf_num=R_finance_B023&userid="+userid,
                  valueField:'val',
                  textField:'text',
                  onLoadSuccess: function (data) {
                  if (data.length>0) {
                $('#bank_A_C').combobox('setValue',data[0].text);
            }
         }
     });
   
}
//}
//初始表单加载
   $('#bene_bank').combobox({
                url:"rule?wf_num=R_finance_B033",
                  valueField:'val',
                  textField:'text',
        
     });
    // method_payment
    $('#method_payment').combobox({
                url:"rule?wf_num=R_finance_B003",
                  valueField:'val',
                  textField:'text',
     });

//报销类型
var WF_DocUnid=$("#WF_DocUnid").val(); 
var initTravelNo = $("#TravelNo").val();
$('#doctype').combobox({
     	onSelect:function(rec) {
     	    //出差计划单，默认按照时间升序，离现在越远的越排在前面
     	    //document.getElementById('cCusCode').value=val.split(",")[1];
            $('#TravelNo').combobox({ 
            	url:"rule?wf_num=R_finance_B060&doctype=" + rec.val,
            	valueField:'id',
            	textField:'text',
            	multiple:false,
            	onLoadSuccess : function() {
        	        var TravelNo = $('#TravelNo').combobox("clear").combobox('getData');
        	        if(TravelNo.length > 0){
        	            for (var i = 0; i < TravelNo.length; i++) { 
                            if (TravelNo[i].id == initTravelNo) {  
                                $('#TravelNo').combobox('select', initTravelNo);//循环判断，如果某项一致，则该项选中  
                            }  
                        }
                        //$('#TravelNo').combobox('select', TravelNo[0].id);//默认选中第一个
        	        }else{
        	            $('#TravelNo').combobox('select', TravelNo);  //
        	        }
            	},
            	onSelect:function(rec) {
            	    var travelUnid = $('#TravelNo').combobox('getValue');
            	    jQuery.ajax({
                        type: "post",
                        async: false,          
                        url: "rule?wf_num=R_finance_B061",
                        dataType: "text",
                        data:{
                            travelUnid: travelUnid
                        },
                        success: function (data) {
                            //alert("travelTotal=====" + data);
                            document.getElementById('travelTotal').value = data;
                        }
                    });
            	}
            }).combobox({"editable":false});
     	    
     	    if(rec.val=='fin_daily'){
     	            $('#dc').innerHTML='';
     	            var item = $('#dg').datagrid('getRows');
     	          //删除视图中的值
                    if (item) {
                      
                        for (var i = item.length - 1; i >= 0; i--) {
                            var index = $('#dg').datagrid('getRowIndex', item[i]);
                         
                            $('#dg').datagrid('deleteRow', index);
                        }
                    }
                 //差旅转换成日常报销类型删除报销天数
                  $.ajax({
                        url:'r?wf_num=R_finance_B026&WF_DocUnid='+WF_DocUnid,
                        dataType:'json',
                        cache:false,
                        async:false, 
                        success:function(data) {
                            res = data;
                      }
                    });
                
     	            $('#controlDiv').hide();
     	           // $('#dg').datagrid('reload');
     	           
     	      //   $('#title').attr("disabled",true); 
            //      $('#title1').attr("disabled",true);
     	         $("#title").val("日 常 费 用 报 销 单 (员工）");//这里赋值的，点击哪个报销类型就加哪个
     	         $("#title1").val("Daily Expenses Reimbursement Form");
     	     
     	       
     	        //隐藏div
     	          $("#fin_day").show();  //fin_travel
     	          $("#fin_travel").hide(); 
     	       }else if(rec.val=='fin_travel_domestic'){//fin_travel_domestic
     	            var item = $('#dg').datagrid('getRows');
                    if (item) {
                        for (var i = item.length - 1; i >= 0; i--) {
                            var index = $('#dg').datagrid('getRowIndex', item[i]);
                            $('#dg').datagrid('deleteRow', index);
                        }
                    }
     	     $('#controlDiv').show();
     	         //$('#title').attr("disabled",true); 
                 //$('#title1').attr("disabled",true);
     	         $("#title").val("境 内 差 旅 费 用 报 销 单 (员工）");
     	         $("#title1").val("Domestic Travel Expense Reimbursement Form");
     	         //$("#title").attr('disabled','disabled');
     	         //$("#title1").attr('disabled','disabled');
     	         //隐藏div
     	         $("#fin_day").hide();  //fin_travel
     	         $("#fin_travel").show(); 
     	   
    
                $('#dc').datagrid({
                    title:"填写出差天数，日期及出发地" ,
                    singleSelect:false,
                  // collapsible:true,
                    method:'get',
                    autoRowHeight:true,
                    fitColumns:true,
                     rownumbers:true,
                    //idField:'WF_OrUnid',
                    //url:'r',
                    queryParams:{
                       
                    },
                    columns:[[
                        {title:'序号',field:'icon',width:30,sortable:false,checkbox:($("#WF_ReadOnly").val()!='true')?true:false},
                        //{title:'主键',field:'WF_OrUnid',hidden:true,sortable:false},
                      
                        {title:'出差天数',field:'travel_days',width:100,sortable:true,
                          editor:{
                            type:'numberbox',
                            precision:2,
                            options:{
                              required: false,
                                width:50
                            }
                        }},
                        {title:'开始时间',field:'sdate',width:100,sortable:true,editor:{
                            type:'datebox',
                            options:{
                                required: false,
                                showSeconds: false   
                            }
                        }},
                        {title:'结束时间',field:'edate',width:100,sortable:true,editor:{
                            type:'datebox',
                            options:{
                                required: false,
                            }
                        }},
                        {title:'出发地',field:'departure',width:100,sortable:true,
                        editor:{
                           
                          type:'textarea',
                            options:{
                                required: false,
                                width:50
                            }
                        }},
                        {title:'目的地',field:'destination',width:100,sortable:true,editor:{
                            type:'textarea',
                            options:{
                                required: false,
                                width:50
                            }
                        }},
                         {title:'途径地',field:'bywayof',width:100,sortable:true,editor:{
                            type:'textarea',
                            options:{
                                required: false,
                                width:50
                            }
                        }},
                         {title:'出差事由',field:'reasons',width:100,sortable:true,editor:{
                            type:'textarea',
                            options:{
                                required: false,
                                width:50
                            }
                        }}
                   
                    ]],
                        onAfterEdit: function (rowIndex, rowData, changes) {//在添加完毕endEdit，保存时触发
                            editFlag = undefined;//重置
                            
                        },
                        onDblClickCell: function (rowIndex, field, value) {//双击该行修改内容
                            if (editFlag != undefined) {
                                $("#dc").datagrid('endEdit', editFlag);//结束编辑，传入之前编辑的行
                            }
                            if (editFlag == undefined) {
                                $("#dc").datagrid('beginEdit', rowIndex);//开启编辑并传入要编辑的行
                                editFlag = rowIndex;
                            }
                        }
                }); 
   
    
    //
            if ($("#WF_ReadOnly").val()!='true' || $('#WF_CurrentNodeid').val()=='T10024') {//凭证接口
              $('#dc').datagrid({
          toolbar: [{//在dategrid表单的头部添加按钮
                        text: "新增",
                        iconCls: "icon-add",
                         handler: function () {
                            if (editFlag != undefined) {
                                $("#dc").datagrid('endEdit', editFlag);//结束编辑，传入之前编辑的行
                            }
                            if (editFlag == undefined) {//防止同时打开过多添加行
                                $("#dc").datagrid('appendRow', {//在指定行添加数据，appendRow是在最后一行添加数据//insertRow
                                  index: 0,    // 行数从0开始计算
                                    row: {
                                       
                                        travel_days: '',
                                        sdate: '',
                                        edate:''
                                    }
                                });
                                $("#dc").datagrid('beginEdit', 0);//开启编辑并传入要编辑的行
                                editFlag = 0;
                            }
                        
                         }
                      
                    }, '-', {//'-'
                        text: "删除",
                        iconCls: "icon-remove",
                        handler: function () {
                            //选中要删除的行
                            var rows = $("#dc").datagrid('getSelections');
                            if (rows.length > 0) {//选中几行的话触发事件
                                $.messager.confirm("提示", "您确定要删除这些数据吗？一旦删除，无法撤销。", function (res) {//提示是否删除
                                    if (res) {
                                      // var codes = new Array()
                                        for (var i = 0; i < rows.length; i++) {
                                        //    codes.push(rows[i].wf_orunid);
                                        var index = $("#dc").datagrid('getRowIndex', rows[i]);
                                            $("#dc").datagrid('deleteRow', index);
                                        }
                                       editFlag = undefined;//新增加
                                    }
                                });
                            }
                        }
                    }, 
                    //增加保存
                    {//'-'
                        text: "保存编辑",
                        iconCls: "icon-save",
                        handler: function () {
                          stopEditRow1(); 
                        }
                    }, 
                   
                    
                    {
                        text: "撤销",
                        iconCls: "icon-redo",
                        handler: function () {
                            if (editFlag!=undefined) {
                                $("#dc").datagrid('rejectChanges');
                                editFlag = undefined;
                            }
                        }
                    }, '-']
              });
            }
                 //测试结束
     	    }
     	    else {
     	       // $('#dg').datagrid('reload');
     	           var item = $('#dg').datagrid('getRows');
                    if (item) {
                        for (var i = item.length - 1; i >= 0; i--) {
                            var index = $('#dg').datagrid('getRowIndex', item[i]);
                            $('#dg').datagrid('deleteRow', index);
                        }
                    }
     	         $('#controlDiv').show();
     	         $("#title").val("境 外 差 旅 费 用 报 销 单 (员工）");
     	         $("#title1").val("Oversea Travel Expense Reimbursement Form");
     	      //   $("#title").attr('disabled','disabled');
     	      //   $("#title1").attr('disabled','disabled');
     	         $("#trval").show();  
     	         $("#fin_day").hide();  //fin_travel
     	         $("#fin_travel").show(); 
     	    
     	    
                  //境外差旅增加出差天数
                  //差旅费增加出差天数
   
                    $('#dc').datagrid({
                        title:"填写出差天数，日期及出发地" ,
                        singleSelect:false,
                      // collapsible:true,
                        method:'get',
                        autoRowHeight:true,
                        fitColumns:true,
                         rownumbers:true,
                        //idField:'WF_OrUnid',
                        url:'r',
                        queryParams:{
                            // wf_num:'D_hr_J013',
                            // staff_no:($("#WF_ReadOnly").val()!='true')?$("#exception_id").val():$("#exception_id").text()
                        },
                        columns:[[
                            {title:'序号',field:'icon',width:30,sortable:false,checkbox:($("#WF_ReadOnly").val()!='true')?true:false},
                            {title:'主键',field:'WF_OrUnid',hidden:true,sortable:false},
                          
                            {title:'出差天数',field:'travel_days',width:100,sortable:true,
                              editor:{
                                type:'numberbox',
                                precision:0,
                                options:{
                                  required: false,
                                    width:50
                                }
                            }},
                            {title:'开始时间',field:'sdate',width:100,sortable:true,editor:{
                                type:'datebox',
                                options:{
                                    required: false,
                                    showSeconds: false   
                                }
                            }},
                            {title:'结束时间',field:'edate',width:100,sortable:true,editor:{
                                type:'datebox',
                                options:{
                                    required: false,
                                }
                            }},
                            {title:'出发地',field:'departure',width:100,sortable:true,
                            editor:{
                               
                              type:'textarea',
                                options:{
                                    required: false,
                                    width:50
                                }
                            }},
                            {title:'目的地',field:'destination',width:100,sortable:true,editor:{
                                type:'textarea',
                                options:{
                                    required: false,
                                    width:50
                                }
                            }},
                             {title:'途径地',field:'bywayof',width:100,sortable:true,editor:{
                                type:'textarea',
                                options:{
                                    required: false,
                                    width:50
                                }
                            }},
                             {title:'出差事由',field:'reasons',width:100,sortable:true,editor:{
                                type:'textarea',
                                options:{
                                    required: false,
                                    width:50
                                }
                            }}
                       
                        ]],
                            onAfterEdit: function (rowIndex, rowData, changes) {//在添加完毕endEdit，保存时触发
                                editFlag = undefined;//重置
                                
                            },
                            onDblClickCell: function (rowIndex, field, value) {//双击该行修改内容
                                if (editFlag != undefined) {
                                    $("#dc").datagrid('endEdit', editFlag);//结束编辑，传入之前编辑的行
                                }
                                if (editFlag == undefined) {
                                    $("#dc").datagrid('beginEdit', rowIndex);//开启编辑并传入要编辑的行
                                    editFlag = rowIndex;
                                }
                            }
                    }); 
                if ($("#WF_ReadOnly").val()!='true') {
                  $('#dc').datagrid({
              toolbar: [{//在dategrid表单的头部添加按钮
                            text: "新增",
                            iconCls: "icon-add",
                            handler: function () {
                                if (editFlag != undefined) {
                                    $("#dc").datagrid('endEdit', editFlag);//结束编辑，传入之前编辑的行
                                }
                                if (editFlag == undefined) {//防止同时打开过多添加行
                                    $("#dc").datagrid('insertRow', {//在指定行添加数据，appendRow是在最后一行添加数据
                                        index: 0,    // 行数从0开始计算
                                        row: {
                                            //staff_no: $("#staff_no").val(),
                                            travel_days: '',
                                            sdate: '',
                                            edate:''
                                        }
                                    });
                                    $("#dc").datagrid('beginEdit', 0);//开启编辑并传入要编辑的行
                                    editFlag = 0;
                                }
                            }
                          
                        }, '-', {//'-'
                            text: "删除",
                            iconCls: "icon-save",
                            handler: function () {
                                //选中要删除的行
                                var rows = $("#dc").datagrid('getSelections');
                                if (rows.length > 0) {//选中几行的话触发事件
                                    $.messager.confirm("提示", "您确定要删除这些数据吗？一旦删除，无法撤销。", function (res) {//提示是否删除
                                        if (res) {
                                         
                                            for (var i = 0; i < rows.length; i++) {
                                           
                                            var index = $("#dc").datagrid('getRowIndex', rows[i]);
                                                $("#dc").datagrid('deleteRow', index);
                                            }
                                           editFlag = undefined;
                                        }
                                    });
                                }
                            }
                        },
                        //增加保存
                    {//'-'
                        text: "保存编辑",
                        iconCls: "icon-save",
                        handler: function () {
                          stopEditRow1(); 
                        }
                    }, 
                        {
                            text: "撤销",
                            iconCls: "icon-redo",
                            handler: function () {
                                if (editFlag!=undefined) {
                                    $("#dc").datagrid('rejectChanges');
                                    editFlag = undefined;
                                }
                            }
                        }, '-']
                    });
                  }
    }
  }
 });
 }  
  

 
 });

 //增加解除锁定表
    var flag = true;
window.onbeforeunload = function () {

if (flag) {
var evt = window.event || arguments[0];
var userAgent = navigator.userAgent;
if (userAgent.indexOf("Firefox") > 0) {
    //   input=top.document.getElementByid("text10");
    //   input[0].value="jerry";
    //$.get(url,function(data){});
     $.ajax({
                url:'r?wf_num=R_finance_B030&WF_DocUnid='+$("#WF_DocUnid").val(),
                //url:url,
                type:'post',
                dataType:'json',
                contentType: "application/json; charset=utf-8",
                //cache:false,
                async:false, 
                success:function(data) {
                  // input[0].value="jerry1";
                  //res = data;
                }
            });
}
}
}